Question Change XML element

Ice

Member
Joined
Jan 25, 2013
Messages
14
Programming Experience
Beginner
Good Day

I have a simple xml document which looks like this.

HTML:
<?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

C#:
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;
            
        }
 
Got it working

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++;

xml.Root.SetElementValue("dayNum", numberValue);
xml.Save("dayValue.xml");

return numberValue;
}
 
Back
Top Bottom