我正在尝试使用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,List和Person元素"继承"该命名空间.您的XPath不匹配,因为您正在选择"无名称空间"中的元素.为了解决绑定到XPath 1.0中命名空间的元素,必须定义命名空间前缀并在XPath表达式中使用它.
你可以让你的XPath更通用,只是匹配local-name,以便它匹配元素,无论它们的命名空间如何:
//*[local-name()='PersonList']/*[local-name()='List']/*[local-name()='Person']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5834 次 |
| 最近记录: |