XML programming Summary (7) -- Query xml documents and xpathxml using XPath objects
(7) query xml documents using XPath objects
XPath is a query language designed to query XML documents. XPath is not a Java language. In fact, XPath is not a complete programming language. There are many things that cannot be expressed using XPath, and even some queries cannot be expressed. Fortunately, we can combine XPath into Java programs so that we can take advantage of the advantages of the two: What Java is good at and what XPath is good. The application programming interfaces (APIS) required for executing XPath queries by Java programs are also different for various XPath engines. Xalan has one API, Saxon uses the other, and other engines use the other API. Java 5 introduces the javax. xml. xpath package, which provides an XPath library independent of the engine and object model.
When calculating an XPath expression in Java, the second parameter specifies the expected return type. There are five possibilities, all of which are named constants in the javax. xml. xpath. XPathConstants class:
- XPathConstants. NODESET
- XPathConstants. BOOLEAN
- XPathConstants. NUMBER
- XPathConstants. STRING
- XPathConstants. NODE
Test code:
1 public class XPathTest {2/** 3 * use an XPath query without a namespace 4 * @ throws Exception 5 */6 @ Test 7 public void testRetrieveOndNode () throws Exception {8 // get the memory model of the xml document 9 DocumentBuilder builder = DocumentBuilderFactory10. newInstance (). newDocumentBuilder (); 11 Document document = builder. parse (new File ("src/main/resource/books. xml "); 12 // create XPathFactory object 13 XPathFactory xPathFactory = XPathFactory. newInstance (); 14 // get the XPath object 15 XPath xPath = xPathFactory. newXPath (); 16 // create an XPath expression object 17 XPathExpression nodeExpr = xPath. compile ("// book [1]"); 18 // execute the XPath expression. Because this expression can only obtain one node, XPathConstants is used. NODE19 Element element = (Element) nodeExpr. evaluate (document, XPathConstants. NODE); 20 NodeList nodes = element. getChildNodes (); 21 for (int I = 0; I <nodes. getLength (); I ++) {22 Node node = nodes. item (I); 23 // obtain the node type 24 short nodeType = node. getNodeType (); 25 if (nodeType = Node. ELEMENT_NODE) {26 // get the node text. getNodeValue () cannot get the node text 27 String text = node. getTextContent (); 28 System. out. println (node. getNodeName () + "--" + text); 29} 30} 31} 32}