How to add a node to XML with XMLBeans XmlObject

wsams picture wsams · Mar 25, 2010 · Viewed 15.1k times · Source

My goal is to take an XML string and parse it with XMLBeans XmlObject and add a few child nodes.

Here's an example document (xmlString),

<?xml version="1.0"?>
<rootNode>
 <person>
  <emailAddress>[email protected]</emailAddress>
 </person>
</rootNode>

Here's the way I'd like the XML document to be after adding some nodes,

<?xml version="1.0"?>
<rootNode>
 <person>
  <emailAddress>[email protected]</emailAddress>
  <phoneNumbers>
   <home>555-555-5555</home>
   <work>555-555-5555</work>
  <phoneNumbers>
 </person>
</rootNode>

Basically, just adding the <phoneNumbers/> node with two child nodes <home/> and <work/>.

This is as far as I've gotten,

XmlObject xml = XmlObject.Factory.parse(xmlString);

Thank you

Answer

Kevin Krouse picture Kevin Krouse · May 6, 2011

Here is an example of using the XmlCursor to insert new elements. You can also get a DOM Node for an XmlObject and using those APIs.

import org.apache.xmlbeans.*;

/**
 * Adding nodes to xml using XmlCursor.
 * @see http://xmlbeans.apache.org/docs/2.4.0/guide/conNavigatingXMLwithCursors.html
 * @see http://xmlbeans.apache.org/docs/2.4.0/reference/org/apache/xmlbeans/XmlCursor.html
 */
public class AddNodes
{
    public static final String xml =
    "<rootNode>\n" +
    "  <person>\n" +
    "    <emailAddress>[email protected]</emailAddress>\n" +
    "  </person>\n" +
    "</rootNode>\n";

    public static XmlOptions saveOptions = new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(2);

    public static void main(String[] args) throws XmlException
    {
        XmlObject xobj = XmlObject.Factory.parse(xml);
        XmlCursor cur = null;
        try
        {
            cur = xobj.newCursor();
            // We could use the convenient xobj.selectPath() or cur.selectPath()
            // to position the cursor on the <person> element, but let's use the
            // cursor's toChild() instead.
            cur.toChild("rootNode");
            cur.toChild("person");
            // Move to </person> end element.
            cur.toEndToken();
            // Start a new <phoneNumbers> element
            cur.beginElement("phoneNumbers");
            // Start a new <work> element
            cur.beginElement("work");
            cur.insertChars("555-555-5555");
            // Move past the </work> end element
            cur.toNextToken();
            // Or insert a new element the easy way in one step...
            cur.insertElementWithText("home", "555-555-5555");
        }
        finally
        {
            if (cur != null) cur.dispose();
        }

        System.out.println(xobj.xmlText(saveOptions));
    }

}