XPath does not work properly when the root tag receives the xmlns property

I am trying to parse an XML file using XPath

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(File); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//PerosnList/List/Person"); 

It took me a long time to see that it does not work, because the root element received the xmlns attribute as soon as I remove the attr, it works fine !, how can I bypass this xlmns attr without deleting it from the file?

xml looks like this:

 <?xml version="1.0" encoding="utf-8"?> <Root xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/vsDal.Entities"> ..... .... <PersonList> ... <List> <Person></Person> <Person></Person> <Person></Person> </List> </PersonList> </Root> 

Thanks.

+4
source share
2 answers

You need to provide a NamespaceContext and a namespace for your expression. See here for an example.

+6
source

The xmlns attribute is larger than a regular attribute. This is a namespace attribute that is used to uniquely classify elements and attributes.

The PersonList , List and Person elements inherit this namespace. Your XPath is not suitable because you select items in "no namespace". To access elements associated with a namespace in XPath 1.0, you must define a namespace prefix and use it in an XPath expression.

You can make your XPath more general and just match local-name so that it matches elements regardless of their namespace:

 //*[local-name()='PersonList']/*[local-name()='List']/*[local-name()='Person'] 
+8
source

Source: https://habr.com/ru/post/1397405/


All Articles