C # How to change Xml node values ​​using Linq

How to replace node some valuevalue with another value using Linq. Finally, I need a string with a replaced value.

Xml:

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

WITH#:

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 */);
0
source share
2 answers

To do this, you can use the method XPathSelectElement:

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);
+3
source

Do not select a value from all nodes, just get the nodes themselves and change the Value property.

+1
source

Source: https://habr.com/ru/post/1655400/


All Articles