Link to home
Start Free TrialLog in
Avatar of CipherIS
CipherISFlag for United States of America

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>

Open in new window

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);
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CipherIS

ASKER

Ah, I was so close.  Thanks.  So, that fixed part of the problem.  Now I have

<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</othervalue>123</key>

Not sure if that matters.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That seems to be causing me a problem.  It is changing
<key ID="123"><othervalue>456</othervalue>123</key>

Open in new window

To
<key ID="ABC"">ABC</key>

Open in new window

Below is being deleted also.
<othervalue>456</othervalue>
I modified it not to save the 456.  Thanks.