Search code examples
c#xmllinqlinq-to-xml

Change the default value of XElement at runtime in C# using LINQ


How can I change the default value of the following XElement in C# using LINQ:

<Automobile>
  <MainBlock>Car</MainBlock>
  <Name>Audi</Name>
  <Value> type="System.Double" min="0" max="100" default="50" resolution="1.0" unit=""</Value>
</Automobile>

The default value is 50. I want to change it to 20.


Solution

  • Here is a LINQ to XML implementation.

    c#

    void Main()
    {
        XDocument xdoc = XDocument.Parse(@"<Automobile>
              <MainBlock>Car</MainBlock>
              <Name>Audi</Name>
              <Value type='System.Double' min='0' max='100' default='50'></Value>
            </Automobile>");
        
        xdoc.Element("Automobile").Element("Value").Attribute("default").SetValue("20");
    }