Convert String XML fragment to Document Node in Java

前端 未结 8 2202
迷失自我
迷失自我 2020-11-28 04:00

In Java how can you convert a String that represents a fragment of XML for insertion into an XML document?

e.g.

String newNode =  \"valu         


        
8条回答
  •  我在风中等你
    2020-11-28 04:07

    For what it's worth, here's a solution I came up with using the dom4j library. (I did check that it works.)

    Read the XML fragment into a org.dom4j.Document (note: all the XML classes used below are from org.dom4j; see Appendix):

      String newNode = "value"; // Convert this to XML
      SAXReader reader = new SAXReader();
      Document newNodeDocument = reader.read(new StringReader(newNode));
    

    Then get the Document into which the new node is inserted, and the parent Element (to be) from it. (Your org.w3c.dom.Document would need to be converted to org.dom4j.Document here.) For testing purposes, I created one like this:

        Document originalDoc = 
          new SAXReader().read(new StringReader(""));
        Element givenNode = originalDoc.getRootElement().element("given");
    

    Adding the new child element is very simple:

        givenNode.add(newNodeDocument.getRootElement());
    

    Done. Outputting originalDoc now yields:

    
    
    
        
            value
        
    
    

    Appendix: Because your question talks about org.w3c.dom.Document, here's how to convert between that and org.dom4j.Document.

    // dom4j -> w3c
    DOMWriter writer = new DOMWriter();
    org.w3c.dom.Document w3cDoc = writer.write(dom4jDoc);
    
    // w3c -> dom4j
    DOMReader reader = new DOMReader();
    Document dom4jDoc = reader.read(w3cDoc);
    

    (If you'd need both kind of Documents regularly, it might make sense to put these in neat utility methods, maybe in a class called XMLUtils or something like that.)

    Maybe there are better ways to do this, even without any 3rd party libraries. But out of the solutions presented so far, in my view this is the easiest way, even if you need to do the dom4j <-> w3c conversions.

    Update (2011): before adding dom4j dependency to your code, note that it is not an actively maintained project, and has some other problems too. Improved version 2.0 has been in the works for ages, but there's only an alpha version available. You may want to consider an alternative, like XOM, instead; read more in the question linked above.

提交回复
热议问题