Increment a xml with c#

◇◆丶佛笑我妖孽 提交于 2019-12-13 21:22:51

问题


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:


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.



来源:https://stackoverflow.com/questions/17821750/increment-a-xml-with-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!