Search code examples
javaxmlxmlbeans

Appending two XmlObjects


I have two XmlObjects using XmlBeans. I want to append one XmlObject as an element of the other.

As an example:

XmlObject 1:

<Object1>
    <attr><attr/>
    <attr><attr/>
<Object1/>

XmlObject 2:

<Object2>
    <attr><attr/>
    <attr><attr/>
<Object2/>

Appended XmlObject:

<Object1>
    <attr><attr/>
    <attr><attr/>
    <Object2>
         <attr><attr/>
         <attr><attr/>
    <Object2/>
<Object1/>

I've found a couple links on merging using NodeLists but they don't seem to be quite what I'm looking for. Any help would be great, Thank you.


Solution

  • I figured it out by using DOM Documents. XmlBeans naturally converts to a DOM Document. From there you can use appending methods to add a child node. Once the node is added you can parse the document back to an XmlObject.

    Please see below:

    XmlObject xmlObject = ...;
    XmlObject xmlObject1 = ...;
    
    Document myDoc = myXmlObject.getMyXmlObject().getDomNode().getOwnerDocument();
    Node newNode = myDoc.importNode(myXmlObject2.getMyXmlObject().getDomNode(), true);
    myDoc.getDocumentElement().appendChild(newNode);
    XmlObject obj = XmlObject.Factory.parse(myDoc);
    

    obj being the newly appended document as an XmlObject.