简体   繁体   中英

XElement C#: How to change the value of XElement?

I have an element that has some value like:

<Element>
     <I id="I01" class="" /> Some Text
</Element>

How do I keep the "I" element but change the "Some Text" in the Element Tag?

You can find the right XText child node of Element and set the value of that. Here's an example, which assumes that it's the first XText node that you're interested in:

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XElement element= XElement.Parse(@"
<Element>
    <I id=""I01"" class="""" /> Some Text
</Element>");
        element.DescendantNodes().OfType<XText>().First().Value = "New value";
        Console.WriteLine(element);
    }
}

Output:

<Element>
  <I id="I01" class="" />New value</Element>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM