Switch to full style
General Java code examples
Post a reply

Parse XML using DOM file and run XPath query

Tue Oct 23, 2012 11:27 pm

Parse XML using DOM file and run XPath query.
Code:

import org
.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;

public class XpathWork {

    public static void main(String[] args)
            throws ParserConfigurationException, SAXException,
            IOException, XPathExpressionException {

        // Reading xml file using DOM
        DocumentBuilderFactory domFactory =
                DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document docment = builder.parse("file.xml");
        XPath xpathObject = XPathFactory.newInstance().newXPath();
        // Run the query
        XPathExpression xpathExpression = xpathObject.compile("//*[count(Info)=3]");
        //Select elements which have three children Info
        System.out.println("Getting elements which have three sub nodes of type Info");
        Object result = xpathExpression.evaluate(docment, XPathConstants.NODESET);
        NodeList allNodes = (NodeList) result;
        for (int i = 0; i < allNodes.getLength(); i++) {
            System.out.println(allNodes.item(i).getNodeName());
        }
        System.out.println("Getting elements which have 3 sub nodes");
        xpathExpression = xpathObject.compile("//*[count(*)=3]");
        //Select elements which have any three children Info
        result = xpathExpression.evaluate(docment, XPathConstants.NODESET);
        allNodes = (NodeList) result;
        for (int i = 0; i < allNodes.getLength(); i++) {
            System.out.println("Node name = " + allNodes.item(i).getNodeName());
        }
    }
}
 


XML file:
Code:
<?xml version="1.0" ?>
<Student>
  <Name>
  <Info/>
  <Info/>
  <Info/>
  </Name>
  <Age>
  <Info/>
  <Info/>
  </Age>
  <Address>
<Info/>
<Info/>
  </Address>
</Student>




Post a reply
  Related Posts  to : Parse XML using DOM file and run XPath query
 evaluate XPath Expression from XML file     -  
 parse XML file using SAX     -  
 Parse URL in java get Protocol,File,Reference,Host and Port     -  
 Web scraping and Parse using java... plz help i really need.     -  
 Load RSS feeds and parse it with JQuery     -  
 Encrypt/Decrypt a file from source file to target file.     -  
 EJB-QL IN where query     -  
 Copy file to file in java code- implementation     -  
 select query example in php     -  
 SQL LIKE query Command     -  

Topic Tags

Java XML