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

时间:2012-02-20 10:35:31

标签: 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");

由于根元素获得了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>

感谢。

2 个答案:

答案 0 :(得分:9)

xmlns属性不仅仅是常规属性。它是namespace attribute,用于唯一限定元素和属性。

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

您可以使XPath更通用,只匹配local-name,以便它与元素匹配,无论其命名空间如何:

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

答案 1 :(得分:7)

您需要为表达式提供NamespaceContext和命名空间。有关示例,请参阅here