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 */);
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);
不要从所有节点中选择Value,而要获取节点本身并更改Value属性。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.