Search code examples
c#xelement

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?


Solution

  • 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>