【问题标题】:How can I get an attribute from the root in a xml file with XPathNavigator?如何使用 XPathNavigator 从 xml 文件的根目录获取属性?
【发布时间】:2011-01-28 15:13:42
【问题描述】:

我想从我的 xml 文件中获取一个属性。该属性在我的根上。看这里的一个例子:

<PriceList ID="003" xmlns="BLA">
  <Items>
    <Item ID="AAK0435">
      <RetailPrice currency="EUR">1.6</RetailPrice>
    </Item>
    <Item ID="AAL0144">
      <RetailPrice currency="EUR">1470</RetailPrice>
    </Item>
  </Items>
</PriceList>

我想获得根上的属性“ID”。我尝试过这样的事情,但他没有进入 foreach 循环。

XPathDocument xPriceDocument = new XPathDocument(priceList.FullName, XmlSpace.None);
                            XPathNavigator xPriceNavigator = xPriceDocument.CreateNavigator();

                            foreach (XPathNavigator xPriceListIdNavigator in xPriceNavigator.Select("PriceList"))
                            {
                                priceListId = xPriceListIdNavigator.GetAttribute("ID", "");
                            }

【问题讨论】:

    标签: xml navigator


    【解决方案1】:

    这是一个命名空间问题。

    <PriceList ID="003" xmlns="BLA">
    

    根元素中的代码xmlns="BLA" 定义了一个带有URI“BLA”的默认命名空间。因此,如果元素名称没有命名空间前缀,则此元素及其后代属于默认命名空间“BLA”。如果元素使用默认命名空间,很容易忘记某个元素位于某个命名空间中,因为没有命名空间前缀。请注意,默认命名空间不适用于属性,仅适用于元素。

    XPath 使用扩展名称(即:由名称空间和本地名称组成的名称对),如果 XPath 表达式中的元素名称没有名称空间前缀,它会选择不属于任何名称空间的元素.要使用 XPath 选择属于某个命名空间的元素,您需要声明该命名空间 URI,将其绑定到前缀,然后在 XPath 表达式中使用此前缀:元素名称组合。

    命名空间是 XML 中的一个基本概念。如果您不熟悉命名空间,请花时间学习和理解它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多