Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

java - Splitting child node from XML file into their own XML files

I have an XML file (on the left) and I want to create multiple files (on the right):

<ParentNode>                                  file1:
    <ChildNode>                               <ParentNode>
        <node></node>                             <ChildNode>
    </childNode>                                      <node></node>
    <ChildNode>                                   </childNode>
        <node></node>                         </ParentNode>
    </childNode>                              file2:
    <ChildNode>                               <ParentNode>
        <node></node>                             <ChildNode>
    </childNode>                                      <node></node>
</ParentNode>                                      </childNode>
                                              </ParentNode>

I am trying to take the first child node from the original XML file and add it to a new one but I keep getting errors around replacing nodes.

I want to do something like the following

 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
 Document newDocument;

 Node firstChild = document.getFirstChild();
 NodeList childNodes = firstChild.getChildNodes();

 Element parentNode;
 for (int i = 1; i < childNodes.getLength(); i++ ) {
     newDocument = docBuilder.newDocument();
     parentNode = newDocument.createElement("ParentNode");
     newDocument.appendChild(parentNode);
     newDocument.getFirstChild().appendChild(childNodes.item(i));
 }

but I get an error

org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.

any help pointing in the right direction appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Nodes in the DOM have a concept of their owning document (hence your WRONG_DOCUMENT_ERR).

So you need to import the node from the original DOM to your new one. See Document.importNode()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...