我需要以编程方式更新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 =&#34; element3&#34; type =&#34; element 3&#34; minOccurs =&#34; 0&#34; maxOccurs =&#34;无限制的#34;)到容器1?
我已经研究过DOM,Xerces,JAXB ......但是没有真正明确的&#34;对&#34;迭代通过XSD并附加一个元素。 Xerces似乎很有希望,但它的文档很少......
谢谢!
答案 0 :(得分:3)
以下是使用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));
关于Java XML的文档相当广泛,有许多教程和代码示例可供使用。有关创建和添加新元素的信息,请参阅Reading XML Data into a DOM,Java: how to locate an element via xpath string on org.w3c.dom.document,Java DOM - Inserting an element, after another;有关已用概念的详细信息,请参见What is the shortest way to pretty print a org.w3c.dom.Document to stdout?。