ehd*_*hdv 6 c# xpath xml-parsing
我正在尝试使用XPath来选择具有Location值的方面的项目,但是目前我的尝试甚至只是选择所有项目失败:系统愉快地报告它找到了0项,然后返回(而不是节点应该由一个foreach循环).我很感激帮助制作我的原始查询或只是让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>
Run Code Online (Sandbox Code Playgroud)
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));
}
Run Code Online (Sandbox Code Playgroud)
除了这个方法还有更多的方法,但是由于这一切都在运行,我假设问题出在这里.调用root.ChildNodes准确返回FacetCategories和Items,让我不知所措我完全.
谢谢你的帮助!
har*_*rpo 20
您的根元素具有命名空间.您需要添加命名空间解析程序并在查询中为元素添加前缀.
本文解释了该解决方案.我修改了你的代码,以便得到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));
}
Run Code Online (Sandbox Code Playgroud)
Ada*_*lls 10
因为您的根节点上有一个XML命名空间,所以XML文档中没有"Item",只有"[namespace]:Item",所以在搜索带有XPath的节点时,需要指定命名空间.
如果您不喜欢这样,可以使用local-name()函数匹配其本地名称(除前缀之外的名称部分)是您要查找的值的所有元素.这有点难看的语法,但它的工作原理.
XmlNodeList xnl = root.SelectNodes("//*[local-name()='Item']");
Run Code Online (Sandbox Code Playgroud)