0

Ok so i have run into a bind with my work. I have a xml document i am trying to change. The value has to change every time a file has downloaded. So basically when file A finishes downloading version.xml has a id that i want to change from "0" to "1". Now with this i can finally set up my launcher the way i want it to be here the code that i have.

private void GetNextNodeID()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(@"version.xml");
        var x = doc.GetElementsByTagName("Product");
        int Max = 0;



        Max++
        XmlElement newElement = doc.CreateElement("Product");
        newElement.SetAttribute("id", Max.ToString());

        doc.Save(@"version.xml");

    }

also here is the xml document

<Table>
<Product>
<Product>0</Product>
<Product_name>Vitare</Product_name>
<Product_version>1.0.0.1</Product_version>
</Product>
</Table>

Now for some reason the code never messes with the xml file please help me figure out how to increment the value!!!!!!!!!

Thank you , Devin Magaro

1 Answers1

2

Currently you're creating a new element using the document, but never actually adding it to the document. You're also trying to set an attribute where previously you had the text within the element itself.

Assuming you really do just want to update the element, I'd personally use LINQ to XML instead of XmlDocument:

var doc = XDocument.Load("version.xml");
// Single() ensures there's only one such element
var element = doc.Descendants("Product").Single(); 
int currentValue = (int) element;
element.SetValue(currentValue + 1);
doc.Save("version.xml");

If you want to update all Product elements, you should loop over doc.Descendants("Product") with a foreach loop.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Now when i run the code and my download finishes i get an error An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll Additional information: Exception has been thrown by the target of an invocation. It happens when im calling the private void from when the download completes – Devin Magaro Jul 23 '13 at 22:07
  • it also points to the Application.Run(new form1()); when the error pops up – Devin Magaro Jul 23 '13 at 22:10
  • @Devin Magaro The problem you have has nothing to do with Jon Skeet's code but visibly you are trying to display this data on WinForms. [You can look @ this](http://stackoverflow.com/questions/3182675/application-runnew-form1-giving-error). On the other, Jon's code won't work with the XML file you have given, you will probably have en error like `Sequence contains more than one element ` since you define two times `` tag. Try to give another name to the outer tag (something like ``. – Mechanical Object Jul 23 '13 at 22:37