How to add a node to XML with XMLBeans XmlObject

15,390

Solution 1

XMLBeans seems like a hassle, here's a solution using XOM:

import nu.xom.*;

Builder = new Builder();
Document doc = builder.build(new java.io.StringBufferInputStream(inputXml));
Nodes nodes = doc.query("person");
Element homePhone = new Element("home");
homePhone.addChild(new Text("555-555-5555"));
Element workPhone = new Element("work");
workPhone.addChild(new Text("555-555-5555"));
Element phoneNumbers = new Element("phoneNumbers");
phoneNumbers.addChild(homePhone);
phoneNumbers.addChild(workPhone);
nodes[0].addChild(phoneNumbers);
System.out.println(doc.toXML()); // should print modified xml

Solution 2

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));
    }

}
Share:
15,390
wsams
Author by

wsams

Hello, I'm a software engineer experienced in a variety of languages and tools. Most of my career has been spent in full-stack development. My favorite languages are Java, Python, JavaScript, Haskell, BASH, and PHP, but I tinker with anything I get my hands on. I enjoy the full life cycle of application development and I'm experienced deploying on bare metal and Docker environments. I'm also comfortable deploying applications into a Kubernetes environment, managing Linux systems, and all manner of scripting.

Updated on June 23, 2022

Comments

  • wsams
    wsams almost 2 years

    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

  • wsams
    wsams about 14 years
    I haven't tried generating XMLBEANS java objects. Any pointers on where to look or start? I'm pretty new to parsing XML with Java. I'll take a look at jdom and xstream as well.
  • Kannan Ekanath
    Kannan Ekanath about 14 years
    It will definitely help if you define clearly what your end goal is. Is it "Adding a few nodes to an existing xml and outputting xml" ?
  • Kannan Ekanath
    Kannan Ekanath about 14 years
    Check this link if you want simple manipulation exampledepot.com/egs/org.w3c.dom/AddText.html
  • wsams
    wsams about 14 years
    Oh sorry, yeah I'd like to take the xml string as input and output the new xml with nodes added as a string. So the input should be xml and the output should be xml with new nodes added.
  • Kannan Ekanath
    Kannan Ekanath about 14 years
  • wsams
    wsams about 14 years
    I haven't had a chance to try this out but I will sometime over the weekend. Someone else recommended dom4j so I'll see which one fits best.
  • wsams
    wsams about 14 years
    I figured out how to do this effectively yesterday. I'll post info soon.
  • MarcoS
    MarcoS about 13 years
    very interesting: I did know XOM: I looks very easy to use! Will keep an eye on it
  • wsams
    wsams almost 12 years
    Yeah, I like this too - never used XOM.
  • wsams
    wsams almost 12 years
    Calm Storm, those worked out alright for me. I think my biggest stumbling block was building a Document object from a String. I was also investigating SAXBuilder.