Back to Library

Java (and Groovy) Native Xpath

As of Java 5, java provides javax.xml.xpath

For a given xml of:

String orderCompleteXml = '''<xml xmlns:ez="" lang="en" xml:lang="en">
<ez:OrderNotification orderId="11290" operatorOrderId="MyReference" >
    <ez:Service id="2938283" type="data" effectiveActivationDate="$effectiveActivationDate"/>
      <ez:Module name="router"/>
      <ez:Module name="game console"/>
    <ez:ExtensionKitInstalled />

Parse the xml into nodes:

StringReader reader = new StringReader( orderCompleteXml );
def builder  = DocumentBuilderFactory.newInstance().newDocumentBuilder()
def records  = builder.parse(new InputSource (reader)).documentElement

Create an xpath expression and evaluate it:

def xpath = XPathFactory.newInstance().newXPath()
// grab some xml based on xpath
DTMNodeList nodes = xpath.evaluate( '//xml/OrderNotification/OrderCompleted/Service', 
records, XPathConstants.NODESET )
println 'found ' + nodes.getLength() + ' nodes'
org.w3c.dom.Node n = nodes.item 0
//  for xml content we can use node.getValue, attributes get more interesting
org.w3c.dom.Node attr = n.getAttributes().item 0
println 'Node name: '  + attr.getNodeName() + ' value ' + attr.getNodeValue()

Set the new value for nodes or attributes

attr.setNodeValue '2005-01-12T00:00:23'
// exporting back to xml 
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File("data_new.xml")));
java_native_xpath.txt · Last modified: 2011/05/23 05:12 by root
RSS - 200 © CrosswireDigitialMedia Ltd