How can I get an attribute from the root in a xml file with XPathNavigator?

311 Views Asked by At

I would like to get an attribute from my xml file. The attribute is on my root. See here an example:

<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>

I would like to get the attribute "ID" on the root. I have try something like this but he doesnt come into the foreach loop.

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

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

There are 1 best solutions below

0
On

This is a namespace issue.

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

Code xmlns="BLA" in your root element defines a default namespace with URI "BLA". Thus this element and its descendants belong to default namespace "BLA" if the element name doesn't have a namespace prefix. It's easy to forget that an element is in some namespace, if it uses the default namespace, because there is no namespace prefix. Note that default namespace doesn't apply to attributes, only elements.

XPath works with expanded names (that is: a name pair consisting of namespace & local name) and if an element name in your XPath expression doesn't have a namespace prefix, it selects elements that don't belong to any namespace. To use XPath to select elements that belong to some namespace, you need to declare that namespace URI, bind it to a prefix and then use this prefix:element-name combination in your XPath expression.

Namespaces are a fundamental concept in XML. If you are not familiar with namespaces, please take time to learn and understand them.