Use of name() function in XPath, starts-with, contains XML XPath 자바 문법
Josep.H.S
2011. 12. 10. 12:27
In the previous section of XPath in Java tutorial we have studied about how to usecount() function in XPath query and in our this section we are going to see how we can implementname() function in the XPath query.
First of all we have created an XML file xmlData.xml. This xml file contains various nodes and we have used name() function in our XPathName class to retrieve name of different nodes according to queries:
Here is the full example code of xmlData.xml as follows:
Now we have declared a class XPathName and in this class we are parsing the XML file with JAXP.First of all we need to load the document into DOM Document object. We have put that xmlData.xmlfile in that current working directory.
Expression "//*[name()='BBB']" will select all elements with name BBB, equivalent with //BBB, "//*[starts-with(name(),'B')]" will select all elements name of which starts with letter B and "//*[contains(name(),'C')]" will select all elements name of which contain letter C.
Here is the full example code of XPathName.java as follows:
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder =
domFactory.newDocumentBuilder();
Document doc = builder.parse("xmlData.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//*[name()='BBB']");
//Select all elements with name BBB, equivalent with //BBB
System.out
.println("Select all elements with " +
"name BBB, equivalent with //BBB");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeName());
}
System.out
.println("Select all elements name "+
"of which starts with letter B");
expr = xpath.compile("//*[starts-with(name(),'B')]");
//Select all elements name of which starts with letter B
result = expr.evaluate(doc, XPathConstants.NODESET);
nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeName());
}
System.out
.println("Select all elements "+
"name of which contain letter C");
expr = xpath.compile("//*[contains(name(),'C')]");
//Select all elements name of which contain letter C
result = expr.evaluate(doc, XPathConstants.NODESET);
nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeName());
}
}
}