我需要用程序更新java中的现有XSD,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="com/company/common" xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="com/company/common/" elementFormDefault="qualified">
<xs:include schemaLocation="DerivedAttributes.xsd" />
<xs:element name="MyXSD" type="MyXSD" />
<xs:complexType name="Containter1">
<xs:sequence>
<xs:element name="element1" type="element1" minOccurs="0"
maxOccurs="unbounded" />
<xs:element name="element2" type="element2" minOccurs="0"
maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="Containter2">
<xs:sequence>
<xs:element name="element3" type="Type1" minOccurs="0" />
<xs:element name="element2" type="Type2" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:schema>
如何以编程方式将具有(name="element3"type="element 3"minOccurs="0"maxOccurs="unbounded")的元素添加到容器1中?
我研究过DOM、Xerces、JAXB。。。但是,并没有真正明确的"正确"方法来遍历XSD并附加元素。Xerces看起来很有前景,但几乎没有相关文档。
谢谢!
以下是如何使用DOM:
// parse file and convert it to a DOM
Document doc = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new InputSource("test.xml"));
// use xpath to find node to add to
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xPath.evaluate("/schema/complexType[@name="Containter1"]",
doc.getDocumentElement(), XPathConstants.NODESET);
// create element to add
org.w3c.dom.Element newElement = doc.createElement("xs:element");
newElement.setAttribute("type", "element3");
// set other attributes as appropriate
nodes.item(0).appendChild(newElement);
// output
TransformerFactory
.newInstance()
.newTransformer()
.transform(new DOMSource(doc.getDocumentElement()), new StreamResult(System.out));
关于JavaXML的文档相当丰富,可以找到许多教程和代码示例。请参阅Reading XML Data into a DOM,Java:how to located a element via xpath string on org.w3c.DOM.dococument,Java DOM-Inserting an element,after each for create and adding a new element,and What is the shortest way to pretty print a org.w3c.DOM.docDocument to stdout?以获取有关所用概念的更详细信息。