当root标记获得xmlns属性时,XPath无法正常工作

ibm*_*123 6 java xml xpath

我正在尝试使用XPath解析xml文件

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");
Run Code Online (Sandbox Code Playgroud)

我花了很多时间才发现它不起作用导致根元素得到xmlns属性一旦我删除了attr它工作正常!,我怎么能解决这个xlmns attr而不从文件中删除它?

xml看起来像这样:

<?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>
Run Code Online (Sandbox Code Playgroud)

谢谢.

Mad*_*sen 10

xmlns属性不仅仅是常规属性.它是一个名称空间属性,用于唯一限定元素和属性.

PersonList,ListPerson元素"继承"该命名空间.您的XPath不匹配,因为您正在选择"无名称空间"中的元素.为了解决绑定到XPath 1.0中命名空间的元素,必须定义命名空间前缀并在XPath表达式中使用它.

你可以让你的XPath更通用,只是匹配local-name,以便它匹配元素,无论它们的命名空间如何:

//*[local-name()='PersonList']/*[local-name()='List']/*[local-name()='Person']
Run Code Online (Sandbox Code Playgroud)


McD*_*ell 8

您需要提供NamespaceContext表达式的命名空间.请看这里的例子.