我需要以编程方式更新 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 看起来很有前途,但几乎没有相关文档。
Thanks!
使用 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 的文档相当广泛,并且有许多教程和代码示例可供找到。看将 XML 数据读入 DOM, Java:如何通过 org.w3c.dom.document 上的 xpath 字符串定位元素, Java DOM - 在另一个元素之后插入一个元素用于创建和添加新元素,以及将 org.w3c.dom.Document 漂亮地打印到标准输出的最短方法是什么?有关所用概念的更多详细信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)