CipherIS
asked on
C# Linq Update XML
Figured out how to update most of the XML elements. I'm having issues with two. I want to updated the Attribute and another value as shown below. I want to update everything that has 123 with ABC. The structure is more complicated. I narrowed it down as that is all that is left that I need to update.
<?xml version="1.0" encoding="utf-8"?>
<myXML>
<person>
<key ID="123">123</key>
</person>
<myXML>
XDocument xdoc = XDocument.Load(xml);
var result = (from x in xdoc.Descendants("key")
where x.Parent.Name.LocalName == "person"
where x.Attribute("ID").Value == sKey
select x).FirstOrDefault();
if result != null
{
result.Element("key").Attribute("ID").SetValue(sKey); //This gives me object not set error.
.......
xdoc.Save(xml);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That seems to be causing me a problem. It is changing
<othervalue>456</othervalu e>
<key ID="123"><othervalue>456</othervalue>123</key>
To<key ID="ABC"">ABC</key>
Below is being deleted also.<othervalue>456</othervalu
ASKER
I modified it not to save the 456. Thanks.
ASKER
<key ID="ABC">123</key>
How do I change the value between <key>???</key>
I guess one thing I should add is that when the XML is generated it is generated as
<key ID="123"><othervalue>456</
Not sure if that matters.