ASPed ASPed - 1 month ago 5x
ASP.NET (C#) Question

XML>XDocument>Element setting value

I am trying to set/change to value for "toPosition". I have the following xml (altered);

<soapenv:Envelope xmlns:soapenv="">
<WorkList xmlns="">

I have the following code;

XDocument xml = XDocument.Load(@"C:\\Test.xml");
XNamespace ns = xml.Root.Name.Namespace;
XElement elm = xml.Root.Element(ns + "Body");
// Works to this point

XElement elm2 = xml.Element("WorkList");
elm2.Element("toPosition").Value = "50";
//elm2 returns a null

I have tried many different variations of code suggested in the numerous postings on this subject but I have been unsuccessful in getting any to work.

Please help!


Element only gets the first immediate child element that matches the specified name. You want an element that's nested 3 levels deep. Descendants will recursively read all child elements that match the name, so this is usually the simplest way to find an element anywhere in the document.

The second thing you need to take into account is the namespace. The namespace of toPosition is the default namespace as inherited from its parent. The default namespace declaration in the parent is declared by the xmlns attribute.

So, putting these together:

XNamespace ns = "";

var element = doc.Descendants(ns + "toPosition").Single();

element.Value = "50";