0

How can I replace the node value some value with another value using Linq. Finally I need a string with the replaced value.

Xml:

<ROOT>
  <A>
    <A1>
      <elementA1></elementA1>
    </A1>
    <A2>
      <elementA2>some value</elementA2>
    </A2>
  </A>
</ROOT>

C#:

XDocument xDoc = XDocument.Parse(@"<ROOT>
                                        <A>
                                          <A1>
                                            <elementA1></elementA1>
                                          </A1>
                                          <A2>
                                            <elementA2>Some value</elementA2>
                                          </A2>
                                        </A>
                                      </ROOT>");

xDoc.Elements("ROOT")
             .Elements("A")
             .Elements("A2")
             .Elements("elementA2")
             .Select(e => e.Value).ToList().ForEach(e => /* change the value */);

2 Answers 2

3

You can use the XPathSelectElement method for this:

var newValue = "New value";

var xDoc = XDocument.Parse(@"<ROOT>
    <A>
        <A1>
            <elementA1></elementA1>
        </A1>
        <A2>
            <elementA2>Some value</elementA2>
        </A2>
    </A>
</ROOT>");

xDoc.XPathSelectElement("/ROOT/A/A2/elementA2").SetValue(newValue);
Sign up to request clarification or add additional context in comments.

Comments

1

Don't select the Value from all the nodes, just get the nodes themselves and change the Value property.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.