NamespaceContext and using namespaces with XPath

后端 未结 5 930
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 13:10

Resolving an xpath that includes namespaces in Java appears to require the use of a NamespaceContext object, mapping prefixes to namespace urls and vice versa.

5条回答
  •  Happy的楠姐
    2020-12-01 13:24

    If you are using Jersey 2 and only have a default XML namespace (xmlns="..."), you can use SimpleNamespaceResolver:

    
    
        
    
    
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    
    Document document = docBuilder.parse(new File("document.xml"));
    String query = "/t:Outer/t:Inner";
    
    XPath xpath = XPathFactory.newInstance().newXPath();
    String xmlns = document.getDocumentElement().getAttribute("xmlns");
    xpath.setNamespaceContext(new SimpleNamespaceResolver("t", xmlns));
    
    NodeList nodeList = (NodeList) xpath.evaluate(query, document, XPathConstants.NODESET);
    
    //nodeList will contain the  element
    

    You can also specify xmlns manually if you want.

提交回复
热议问题