how to retrieve XML data using XPath which contains namespace in Java?

后端 未结 2 2022
栀梦
栀梦 2020-12-18 06:19

i know there are plenty of this topic in this page but sadly, i still cant get my solution..

here is my xml code:



        
相关标签:
2条回答
  • 2020-12-18 07:07

    You need to use a NamespaceContext for your XPath expression. You can read more about how to do this here

    0 讨论(0)
  • 2020-12-18 07:08

    You are going to have to create a subclass of javax.xml.namespace.NamespaceContext and set it on xpath:

    xpath.setNamespaceContext(new NamespaceContext() {
    
        @SuppressWarnings("rawtypes")
        @Override
        public Iterator getPrefixes(final String namespaceURI) {
            return Collections.singleton("ns1").iterator();
        }
    
        @Override
        public String getPrefix(final String namespaceURI) {
            return "ns1";
        }
    
        @Override
        public String getNamespaceURI(final String prefix) {
            return "http://www.sea.com";
        }
    });
    

    Then you can add the namespace prefix to the XPath expression:

    XPathExpression expr = xpath.compile("//ns1:PayrollCost/*/text()");
    
    0 讨论(0)
提交回复
热议问题