06 November 2012

All about XPath

this is the sample xml.


DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse("C:/templates.xml");

 XPath xpath=XPathFactory.newInstance().newXPath();
 XPathExpression expr=xpath.compile("//templates/template[1]/label/text()");
 NodeList ns=(NodeList)expr.evaluate(dom,XPathConstants.NODESET);

 for(int i=0;i    {
        System.out.println(ns.item(i).getNodeValue());

 }

here the output will be the value of the label of 1st template tag.



XPathExpression expr=xpath.compile("//templates/template/label/text()");
  NodeList ns=(NodeList)expr.evaluate(dom,XPathConstants.NODESET);

here the output will be the value of all the labels present in all the template tags


XPathExpression expr=xpath.compile("//templates/template/@name");
NodeList ns=(NodeList)expr.evaluate(dom,XPathConstants.NODESET);

here the output will be the values of attribute name of all the template tags



 XPathExpression expr=xpath.compile("//templates/template");
 NodeList ns=(NodeList)expr.evaluate(dom,XPathConstants.NODESET);
    for(int i=0;i       NamedNodeMap la=ns.item(i).getAttributes();
    System.out.println(la.getNamedItem("name").getNodeValue());

}

if a tag has more than 1 attribute, then , values of the attributes can be fetched like this.


  XPathExpression expr=xpath.compile("//templates/template/@name");
    NodeList ns=(NodeList)expr.evaluate(dom,XPathConstants.NODESET);
    for(int i=0;i         ns.item(i).setNodeValue("this is test");
         Transformer xformer = TransformerFactory.newInstance().newTransformer();
         xformer.transform(new DOMSource(dom), new StreamResult(new File("C:/templates.xml")));
    }


This code is changing the value of the specified attribute,here the attribute name is 'name' and saving in the xml





Delicious add to del.icio.us saved by 0 users

No comments:

Post a Comment