Search code examples
xmlc#-4.0linq-to-xmlxelement

Update a specific XML Element without caring what value is there


Although there are a lot of examples on how to do this, I seem to be stuck and I cannot find anything out there to help me. I want to update the value of the index without testing it's previous value. I know this must be easy but I'm stumped.

I initially create my xml document

XDocument master;
master = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("ERoot",
    new XElement("EHeader"),
    new XElement("EData")));
master.Save(MasterXml);

and later add the index node

myIndex = 0;
XElement treename = XElement.Load(MasterXml);
XElement head = treename.Element("EHeader");

head.Add(new XElement("Index", myIndex));
treename.Save(MasterXml);

and the XML file looks ok

<?xml version="1.0" encoding="UTF-8"?>
<ERoot> 
    <EHeader> 
        <Index>0</Index> 
    </EHeader> 
    <EData/> 
</ERoot>

So, how do I update the Index value without caring what value was there before. All the examples I see are selecting the ... something.Value == "0" ... and I may not know what it is. I just want to overwrite and value that may be there.

Thanks


Solution

  • Try

    master.Element("ERoot").Element("EHeader").Element("Index").SetValue(3);
    

    or

    master.Descendants("Index").First().SetValue(3);
    

    P.S. You cant't get element EHeader by

    treename.Element("EHeader");
    

    must be

    treename.Element("ERoot").Element("EHeader");