当根标记获得 xmlns 属性时,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>
谢谢。
I'm 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 alot of time to see that it's not working cause the root element got xmlns attribute
once i remove the attr it works fine!, how can i workaround this xlmns attr without deleting it from the file ?
The 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
xmlns
属性不仅仅是一个常规属性。它是一个 命名空间属性,用于唯一限定元素和属性。PersonList
、List
和Person
元素“继承”该命名空间。您的 XPath 不匹配,因为您正在选择“无命名空间”中的元素。为了寻址绑定到 XPath 1.0 中的命名空间的元素,您必须定义命名空间前缀并在 XPath 表达式中使用它。您可以使 XPath 更加通用,只匹配
local-name
,这样它就可以匹配元素,而不管其命名空间如何:The
xmlns
attribute is more than just a regular attribute. It is a namespace attribute which are used to uniquely qualify elements and attributes.The
PersonList
,List
, andPerson
elements "inherit" that namespace. Your XPath isn't matching because you are selecting elements in the "no namespace". In order to address elements bound to a namespace in XPath 1.0 you must define a namespace-prefix and use it in your XPath expression.You could make your XPath more generic and just match on the
local-name
, so that it matches the elements regardless of their namespace:您需要提供
NamespaceContext
和您的表达式的命名空间。有关示例,请参阅此处。
You need to provide a
NamespaceContext
and namespace your expression. See here for an example.