你的位置:首页 > Java教程

[Java教程]XML编程总结(七)——使用XPath对象查询xml文档

(七)使用XPath对象查询

 XPath,一种为查询

在 Java 中计算 XPath 表达式时,第二个参数指定需要的返回类型。有五种可能,都在javax.

  • XPathConstants.NODESET
  • XPathConstants.BOOLEAN
  • XPathConstants.NUMBER
  • XPathConstants.STRING
  • XPathConstants.NODE

测试代码:

 1 public class XPathTest { 2   /** 3    * 使用不带命名空间的XPath查询 4    * @throws Exception 5   */ 6   @Test 7   public void testRetrieveOndNode() throws Exception{ 8     //获得 9     DocumentBuilder builder = DocumentBuilderFactory10     .newInstance().newDocumentBuilder();11     Document document = builder.parse(new File("src/main/resource/books.));12     //创建XPathFactory对象13     XPathFactory xPathFactory = XPathFactory.newInstance();14     //获得XPath对象15     XPath xPath = xPathFactory.newXPath();16     //创建XPath表达式对象17     XPathExpression nodeExpr = xPath.compile("//book[1]");18     //执行XPath表达式,因为该表达式只能获得一个节点,所以用XPathConstants.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       //获得节点类型24       short nodeType = node.getNodeType();25       if(nodeType==Node.ELEMENT_NODE){26         //获得节点文本,getNodeValue()无法获得节点的文本27         String text=node.getTextContent();28         System.out.println(node.getNodeName()+"--"+text);29       }30     }31   }32 }