C#XPath没有找到任何东西
问题描述:
我想使用XPath来选择具有Location
值的方面的项目,但是当前我甚至尝试仅选择所有项目失败:系统愉快地报告它找到了0项,然后返回(而不是节点应该由foreach
循环处理)。我会很感激帮助,无论是进行原始查询还是只让XPath工作。C#XPath没有找到任何东西
XML
<?xml version="1.0" encoding="UTF-8" ?>
<Collection Name="My Collection" SchemaVersion="1.0" xmlns="http://schemas.microsoft.com/collection/metadata/2009" xmlns:p="http://schemas.microsoft.com/livelabs/pivot/collection/2009" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FacetCategories>
<FacetCategory Name="Current Address" Type="Location"/>
<FacetCategory Name="Previous Addresses" Type="Location" />
</FacetCategories>
<Items>
<Item Id="1" Name="John Doe">
<Facets>
<Facet Name="Current Address">
<Location Value="101 America Rd, A Dorm Rm 000, Chapel Hill, NC 27514" />
</Facet>
<Facet Name="Previous Addresses">
<Location Value="123 Anywhere Ln, Darien, CT 06820" />
<Location Value="000 Foobar Rd, Cary, NC 27519" />
</Facet>
</Facets>
</Item>
</Items>
</Collection>
C#
public void countItems(string fileName)
{
XmlDocument document = new XmlDocument();
document.Load(fileName);
XmlNode root = document.DocumentElement;
XmlNodeList xnl = root.SelectNodes("//Item");
Console.WriteLine(String.Format("Found {0} items" , xnl.Count));
}
还有更多比这个方法,但因为这是获取运行我假设所有的问题就出在这里。致电root.ChildNodes
准确地返回FacetCategories
和Items
,所以我完全无所适从。
感谢您的帮助!
答
您的根元素有一个名称空间。您需要添加一个名称空间解析器并在查询中为元素添加前缀。
This article解释了解决方案。我修改了你的代码,以便得到1结果。
public void countItems(string fileName)
{
XmlDocument document = new XmlDocument();
document.Load(fileName);
XmlNode root = document.DocumentElement;
// create ns manager
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(document.NameTable);
xmlnsManager.AddNamespace("def", "http://schemas.microsoft.com/collection/metadata/2009");
// use ns manager
XmlNodeList xnl = root.SelectNodes("//def:Item", xmlnsManager);
Response.Write(String.Format("Found {0} items" , xnl.Count));
}
答
因为你有你的根节点上的XML命名空间,也为你的XML文档中的“项目”没有这样的事,只有“[命名空间]:项目”,因此对于使用XPath的节点搜索时,你需要指定命名空间。
如果您不喜欢那样,您可以使用local-name()函数来匹配所有其本地名称(除前缀之外的名称部分)是您正在查找的值的元素。这是一个有点丑陋的语法,但它的工作原理。
XmlNodeList xnl = root.SelectNodes("//*[local-name()='Item']");