Tuesday, August 20, 2013

Create XML With Only XPath and Values

Today I found myself needing to create a pretty straight forward XML document. The catch was I was taking values from a database that included the xpath address and a value, and from there I had to create the document. It's not incredibly complicated but briefly googling it didn't turn up any results so here is my solution, using the dom4j (1.6.1) API. (Other dependencies include Jaxen, Apache Commons, and log4j).


The real meat of this solution is the addElementToParent method. What it does it searches for the parent element of the provided xpath. If it doesn't find the parent in the document it will create it via a recursive call. Another trick is it will create any siblings that are needed in case the parent has an index (like /root/parent[3]). Once all the prerequisite elements are created it will then create the element we originally asked for.

This example will create this XML even though we only really tell it to create 5 elements. (the elements depend on the data element so it is created automatically.

4 comments:

  1. Hi Brett, did you remove this solution? I was looking for something similar, and could use it to get started!

    Thanks

    ReplyDelete
  2. It still show up for me. Here is a link to the files on github: https://gist.github.com/bmchild/6285705#file-xpathutils-java

    ReplyDelete
  3. Hi Brett,
    It is a nice piece of work. Do you also have a version that handles Attributes??
    Thanks

    ReplyDelete
  4. Please post if this works in the case of attributes.It worked for the elements.Any pointers would be of great help

    ReplyDelete