h1ghfive
h1ghfive

Reputation: 206

How to retrieve correct XPath expression

I've got a problem with the following, let's consider this XML document :

<FEATURE xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <LINES xmlns="namespace1">
  <LINE>
    <AMOUNT>5000</AMOUNT>
    ......
  </LINE>
  <LINE>
    <AMOUNT>6000</AMOUNT>
  </LINE>
 </LINES>
</FEATURE>

I can't figure out how to modify for exemple the AMOUNT value of the first LINE.

I have tried many things, like the following :

var doc = XDocument.Load(doc);
var xmn = new XmlNamespaceManager(new NameTable());
xmn.AddNamespace(string.Empty, "namespace1");

var element = doc.XPathSelectElement("/FEATURE/LINES/LINE[1]", xmn);

element is always null and I can't figure out why. I have tried this : http://www.xmlplease.com/update-xml-linq with removing the id attribute the XPath /products/product[1] works great...

Any advice would be appreciated.

Upvotes: 0

Views: 96

Answers (2)

Samer_Azar
Samer_Azar

Reputation: 433

XmlNodeList nodeList = root.SelectNodes("/FEATURE/LINES/LINE"); // selecting the first LINE node
foreach(XmlNode node in nodeList) 
{
   if(node.Name == "AMOUNT")
   {
      string anyValue = "7000"
      node.InnerText = value;
   }
}

Upvotes: 0

Juan Ayala
Juan Ayala

Reputation: 3518

giving the default NS a name

xmn.AddNamespace("my", "namespace1");

and writing xpath like this

doc.XPathSelectElement("/FEATURE/my:LINES/my:LINE[1]", xmn);

worked for me :-)

Upvotes: 2

Related Questions