10

我正在尝试使用 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>

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准确返回FacetCategoriesand Items,所以我完全不知所措。

谢谢你的帮助!

4

2 回答 2

27

您的根元素有一个命名空间。您需要添加命名空间解析器并为查询中的元素添加前缀。

本文解释了解决方案。我已经修改了您的代码,使其得到 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));
}
于 2010-04-07T16:06:29.333 回答
13

因为您的根节点上有一个 XML 命名空间,所以您的 XML 文档中没有“Item”之类的东西,只有“[namespace]:Item”,所以在使用 XPath 搜索节点时,您需要指定命名空间。

如果您不喜欢这样,您可以使用 local-name() 函数来匹配其本地名称(前缀以外的名称部分)是您要查找的值的所有元素。这是一个有点难看的语法,但它有效。

XmlNodeList xnl = root.SelectNodes("//*[local-name()='Item']");
于 2010-04-07T16:33:58.190 回答