Tue Oct 23, 2012 11:27 pm
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 version="1.0" ?>
<Student>
<Name>
<Info/>
<Info/>
<Info/>
</Name>
<Age>
<Info/>
<Info/>
</Age>
<Address>
<Info/>
<Info/>
</Address>
</Student>
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.