Peter Cottle

Peter Cottle

  • NA
  • 14
  • 6.7k

Change XML element in C#

Jan 25 2013 2:02 AM
Good Day

I have a simple xml document which looks like this.

<?xml version="1.0" encoding="utf-8" ?>
<DayNo>
  <dayNum>1</dayNum>
</DayNo>

I'm using C# and Linq to extract the value from the dayNum element of the document but
when I try to set value using my code it bombs below is the code I'm using. It all works
fine till I try to do xml.Element("dayNum").SetValue(numberValue.ToString()); I would appreciate any
assistance.

Thank you

 public static int getValue()
        {
            XDocument xml = XDocument.Load(@"dayValue.xml");
            var resultSet = from x in xml.Descendants("DayNo")
                            select x.Element("dayNum");

            string numValue = resultSet.ElementAt(0).Value;
            int numberValue = Int32.Parse(numValue);

            numberValue += 1;

            xml.Element("dayNum").SetValue(numberValue.ToString());

            return numberValue;
           
        }

Answers (2)