Java – What’s the best way to merge two XML Strings with the same tag names

javaxml

For example, say I have two XML Strings that I want to merge:

<Test>
    <A>false</A>
    <B>true</B>
    <C>Transfers!</C>
</Test>

<Test2>
    <A>false</A>
    <B>false</B>
</Test2>

Where the final result looks like (notice, B is now false, because I would like a place to do some sort of logic to determine the final "merged values", in this example, a method would take in two strings, false, and true, and do some AND logic and return "false")

<Test>
    <A>false</A>
    <B>false</B>
    <C>Transfers!</C>
</Test>

I am thinking of either doing it all by hand, using JAX-B & XPath, or XStream Marshal/Unmarshallers. Does anyone have an example of the best & most dynamic way to do this?

The element names will change, they will not always be "A" and "B", but the two XML strings I pass in will always have some elements in common, but sometimes one XML String/Document may have one or more elements that don't exist in the other document, and in this case those need to be in the final XML result as is.

Best Answer

XML and JaxB will allow you to unmarshall these xml strings/documents into objects. After that you would feed these two objects as input to a Merge(thing1,thing2) method that then returns the merged object. You then marshall into an xml string/document and you are complete.

As far as making it "dynamic", that wouldn't be prudent. You would want to define logic on how each of the potential fields is populated (assuming there will be non-boolean fields).

Note: the marshal/unmarshal gives an opportunity to enforce the schema on the given data. If you parse the document by hand then you will be forced to validate the xml formatting and validate against a schema, which doesn't sound like a great idea considering that there are libraries out there that every soap web service is already using.