-->

How to Programmatically Update and Add Elements to

2019-07-21 19:10发布

问题:

I need to programatically update an an existing XSD in java that looks like this:

<?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>

How can programatically and add an element that has (name="element3" type="element 3" minOccurs="0" maxOccurs="unbounded") to Container 1?

I've looked into DOM, Xerces, JAXB...but there is no really clear "right" way iterate though an XSD and append an element. Xerces seems promising but there is little documentation for it..

Thanks!

回答1:

Here's how to do it using 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));

The documentation on the Java XML is rather extensive and there are many tutorials and code examples to be found. See 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? for more detailed information on used concepts.