Monday, June 01, 2009

Using XPath in Java

Given the following xml document:
<hosts>
  <host name="starship" port="8080"/>
  <host name="firefly" port="8180"/>
</hosts>
this is how you can use the javax.xml.xpath library to run an XPath query in order to obtain a list of host names:
//create a document
DocumentBuilderFactory domFactory = 
                     DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("file.xml");

//create the xpath expression
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//host/@name");

//run the xpath query
Object result = expr.evaluate(doc, XPathConstants.NODESET);

//read results
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getNodeValue());
}

2 comments:

  1. Really Thanks re.. i got to Much about XPATH

    Regards
    Shivaling Sannalli

    ReplyDelete
  2. Anonymous2:39 AM

    nice,thanks!

    ReplyDelete

Note: Only a member of this blog may post a comment.