Convert String XML fragment to Document Node in Java

前端 未结 8 2201
迷失自我
迷失自我 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

    Here's yet another solution, using the XOM library, that competes with my dom4j answer. (This is part of my quest to find a good dom4j replacement where XOM was suggested as one option.)

    First read the XML fragment into a nu.xom.Document:

    String newNode = "value"; // Convert this to XML
    Document newNodeDocument = new Builder().build(newNode, "");
    

    Then, get the Document and the Node under which the fragment is added. Again, for testing purposes I'll create the Document from a string:

    Document originalDoc = new Builder().build("", "");
    Element givenNode = originalDoc.getRootElement().getFirstChildElement("given");
    

    Now, adding the child node is simple, and similar as with dom4j (except that XOM doesn't let you add the original root element which already belongs to newNodeDocument):

    givenNode.appendChild(newNodeDocument.getRootElement().copy());
    

    Outputting the document yields the correct result XML (and is remarkably easy with XOM: just print the string returned by originalDoc.toXML()):

    
    value
    

    (If you wanted to format the XML nicely (with indentations and linefeeds), use a Serializer; thanks to Peter Štibraný for pointing this out.)

    So, admittedly this isn't very different from the dom4j solution. :) However, XOM may be a little nicer to work with, because the API is better documented, and because of its design philosophy that there's one canonical way for doing each thing.

    Appendix: Again, here's how to convert between org.w3c.dom.Document and nu.xom.Document. Use the helper methods in XOM's DOMConverter class:

    // w3c -> xom
    Document xomDoc = DOMConverter.convert(w3cDoc);
    
    // xom -> w3c
    org.w3c.dom.Document w3cDoc = DOMConverter.convert(xomDoc, domImplementation);  
    // You can get a DOMImplementation instance e.g. from DOMImplementationRegistry
    

提交回复
热议问题