Splitting child node from XML file into their own XML files

前端 未结 2 1842
予麋鹿
予麋鹿 2020-12-21 20:40

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

                                  file1:
    

        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-21 21:27

    From Java documentation,

    Use cloneNode method.

    SUMMARY:

    public Node cloneNode(boolean deep)
    

    Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes. The duplicate node has no parent; ( parentNode is null.).

    Cloning an Element copies all attributes and their values, including those generated by the XML processor to represent defaulted attributes, but this method does not copy any text it contains unless it is a deep clone, since the text is contained in a child Text node. Cloning an Attribute directly, as opposed to be cloned as part of an Element cloning operation, returns a specified attribute ( specified is true). Cloning any other type of node simply returns a copy of this node.

    Note that cloning an immutable subtree results in a mutable copy, but the children of an EntityReference clone are readonly . In addition, clones of unspecified Attr nodes are specified. And, cloning Document, DocumentType, Entity, and Notation nodes is implementation dependent.

    EDIT :

    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import javax.xml.transform.*; 
    import javax.xml.transform.dom.DOMSource; 
    import javax.xml.transform.stream.StreamResult;
    
    public class Test{
     static public void main(String[] arg) throws Exception{
    
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     DocumentBuilder builder = factory.newDocumentBuilder();
     Document doc = builder.parse("foo.xml");
    
     TransformerFactory tranFactory = TransformerFactory.newInstance(); 
     Transformer aTransformer = tranFactory.newTransformer(); 
    
    
     NodeList list = doc.getFirstChild().getChildNodes();
    
     for (int i=0; i

提交回复
热议问题