Search code examples
javaxmlxmlbeans

How to add a node to XML with XMLBeans XmlObject


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


Solution

  • 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