简体   繁体   中英

Splitting xml nodes

I have this xml:

<Forms>
<Form ID="230688" TemplateID="1111" DocType="1">
    <Field name="topmostSubform[0].Page1[0].Street[0]" value="street" />
    <Field name="topmostSubform[0].Page1[0].HouseNo[0]" value="18" />
</Form>
<Form ID="230645" TemplateID="5444" DocType="8">
    <Field name="topmostSubform[0].Page1[0].city[0]" value="city_name" />
    <Field name="topmostSubform[0].Page1[0].number[0]" value="345354" />
</Form>
<Form ID="230690" TemplateID="1123" DocType="8">
    <Field name="topmostSubform[0].Page1[0].group[0]" value="group" />
    <Field name="topmostSubform[0].Page1[0].phone[0]" value="phone" />
</Form>

I want to produce 4 xml's which every one of them consist of one single form node.

That is produce (one for each Form node):

<Forms>
<Form ID="230688" TemplateID="1111" DocType="1">
    <Field name="topmostSubform[0].Page1[0].Street[0]" value="street" />
    <Field name="topmostSubform[0].Page1[0].HouseNo[0]" value="18" />
</Form>
</Forms>

I tried:

NodeList nodeList = (NodeList) xpath.evaluate("//Forms//Form", parser.doc,XPathConstants.NODESET);
for(int i=0; i<nodeList.getLength(); i++)
            {
                Document outputDoc = _docBuilder.newDocument();
                Element rootElement = outputDoc.createElement("Forms");
                Node childNode = nodeList.item(i);
                rootElement.appendChild(childNode);
                outputDoc.appendChild(rootElement); .....

But that gives an exception: "WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it."

You want to use Document.importNode()

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node. The returned node has no parent; (parentNode is null).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM