如何以编程方式更新和添加元素到 XSD

How to Programmatically Update and Add Elements to an XSD

我需要以编程方式更新 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...但是没有真正明确的 "right" 方法遍历 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));

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 for creating and adding a new Element, and What is the shortest way to pretty print a org.w3c.dom.Document to stdout?