3

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>joefoo@example.com</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>joefoo@example.com</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
  • 2,499
  • 7
  • 40
  • 51

4 Answers4

7

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>joefoo@example.com</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));
    }

}
Kevin Krouse
  • 610
  • 6
  • 9
3

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
MarcoS
  • 13,386
  • 7
  • 42
  • 63
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
0

Method getDomNode() gives you access to the underlying W3C DOM Node. Then you can append childs using W3C Document interface.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
jseba
  • 1
0

It may be a little difficult to manipulate the objects using just the XmlObject interface. Have you considered generating the XMLBEANS java objects from this xml?

If you don't have XSD for this schema you can generate it using XMLSPY or some such tools.

If you just want XML manipulation (i.e, adding nodes) you could try some other APIs like jdom or xstream or some such thing.

Kannan Ekanath
  • 16,759
  • 22
  • 75
  • 101
  • 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. – wsams Mar 26 '10 at 15:27
  • 1
    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 Mar 26 '10 at 15:38
  • 1
    Check this link if you want simple manipulation http://exampledepot.com/egs/org.w3c.dom/AddText.html – Kannan Ekanath Mar 26 '10 at 15:40
  • 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. – wsams Mar 26 '10 at 19:55
  • 1
    So these links http://exampledepot.com/egs/org.w3c.dom/AddNode.html and http://exampledepot.com/egs/org.w3c.dom/AddText.html do not solve your problem ? – Kannan Ekanath Mar 26 '10 at 20:22
  • 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 Mar 27 '10 at 00:03
  • I figured out how to do this effectively yesterday. I'll post info soon. – wsams Mar 31 '10 at 17:49
  • 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. – wsams Aug 01 '12 at 17:34