Reputation: 269
How do we update the a node name with a new value using LINQ?
<test xmlns="http://www.mydomain.com/test/xyz" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
<Ribbon1>test</Ribbon1>
<Ribbon2>test</Ribbon2>
</test>
I was trying as below:
var query = from lst in XElement.Load(fileLoc).Elements(ns + "Ribbon1")
select lst.FirstNode ;
The below code is working now:
XNamespace ns = @"http://www.mydomain.com/test/xyz";
XElement xElement = XElement.Load(fileLoc);
foreach (XElement descendant in xElement.Descendants(ns + "Ribbon1"))
descendant.Value = "Borra";
xElement.Save(fileLoc);
Upvotes: 0
Views: 66
Reputation: 269
XNamespace ns = @"http://www.mydomain.com/test/xyz";
XElement xElement = XElement.Load(fileLoc);
foreach (XElement descendant in xElement.Descendants(ns + "Ribbon1"))
descendant.Value = "Borra";
xElement.Save(fileLoc);
Upvotes: 1
Reputation: 273691
Your code use Elemnts
and that only looks at the given level. To find something at an arbitrary level:
//XElement.Load(fileLoc).Elements(ns + "Ribbon1")
XElement.Load(fileLoc).Descendants(ns + "Ribbon1")
or to adhere to the structure:
XElement.Load(fileLoc).Element(ns + "test").Elements(ns + "Ribbon1")
be careful about Element() and Elements()
Upvotes: 2