Reputation: 18097
I have XML string which I am trying to read with code
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(XMLString);
XmlNode node = xmlDoc.SelectSingleNode("//cart/cart-item/url/text()");
Console.WriteLine(node.Value);
But node
is always null. Could anyone explain what is wrong?
<order xmlns="http://ws.plimus.com">
<order-id>8301446</order-id>
<ordering-shopper>
<shopper-id>25879327</shopper-id>
</ordering-shopper>
<cart>
<charged-currency>USD</charged-currency>
<cart-item>
<sku>...</sku>
<quantity>1</quantity>
<url>
https://ws.plimus.com:443/services/2/subscriptions/9433117
</url>
<item-sub-total>9.00</item-sub-total>
</cart-item>
<tax>0.00</tax>
<tax-rate>0</tax-rate>
<total-cart-cost>9.00</total-cart-cost>
</cart>
</order>
Upvotes: 0
Views: 156
Reputation: 23626
By default XPath considers unprefixed names to be in "no namespace". You should use XmlNamespaceManager
to resolve xmlns
XmlDocument xmlDoc = new XmlDocument();
XmlNamespaceManager nm = new XmlNamespaceManager(xmlDoc.NameTable);
nm.AddNamespace("ns", "http://ws.plimus.com");
xmlDoc.LoadXml(xmlString);
XmlNode node = xmlDoc.SelectSingleNode("//ns:cart/ns:cart-item/ns:url/text()", nm);
Console.WriteLine(node.Value);
Edit: If you have the possibility to change xml root element to
<order xmlns:ns="http://ws.plimus.com">
then you don't need to specify 'ns' in XPath every time, it would look like //cart/cart-item/url/text()
.
XmlNamespaceManager
configuration as shown in example is required anyway
Upvotes: 6
Reputation: 399
When you specify // in xpath it determines starting from root element, so your xpath should be:
XmlNode node = xmlDoc.SelectSingleNode("//order/cart/cart-item/url/text()");
Upvotes: -1