XPathSet in Java

howto Add comments

After thrashing with sed, awk, and various other attempts to cleanly edit XML, I kept thinking “why don’t I use xpathset”?

xpathset is a tool based on an example in xmlsoft — I’ve got a copy on my cnp-tools project — but it runs on Linux, and my employer uses Windows for all supported installs of its Java-based product. That seems a non-happener.

Sometime last night, I remembered that we are a Java company, and I can compile and share Java code without incurring support issues, additional compiler toolchains, licenses, etc while still leveraging the underlying strength of my coworkers where needed.

From 7pm to 9pm I built XPathSet.java using XPathTool.java to effect behavior similar to xpathset; it took another 4 hours to clean up and document, but it’s available if you would like to re-use it. Although I didn’t open up xpathset while I was working (xpathset based on an xmlsoft example, hence MIT license), I’m certain I reused the same concepts I used in that tool, so I should license as MIT.

In this example, we are (and it is sequential!):

  1. load input.xml
  2. registering “textfile.txt” as the replacement value
  3. searching for XPath “//ScanTask[@name=’scanExample1′]/@file” and replacing all matches for “textfile.txt”
  4. writing the result to output.xml

The example I did this for is a filename fix in an Axeda EDD_TEXT.xml file. It is possible to read and write the same file, effecting an in-place edit — with Axeda, there may be a timing issue: I’ve found that the file cannot be written on occasion.

The side-effect of the underlying javax.xml.transform technology used is that the attributes are alphabetized on the way in or out of the DOM, so don’t be too surprised if your attributes are re-ordered. Also, indentation may change.

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in