用c#增加一个xml [英] Increment a xml with c#

查看:42
本文介绍了用c#增加一个xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我的工作遇到了麻烦.我有一个要更改的 xml 文档.每次下载文件时,该值都必须更改.所以基本上当文件 A 完成下载 version.xml 时,我想将一个 ID 从0"更改为1".现在有了这个,我终于可以按照我希望的方式设置我的启动器了.

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");

    }

这里也是xml文档

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

现在出于某种原因,代码永远不会弄乱 xml 文件,请帮我弄清楚如何增加值!!!!!!!!!

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

谢谢你,德文·马加罗

推荐答案

目前您正在使用文档创建一个新元素,但从未真正将其添加到文档中.您还尝试设置一个 属性,之前您在元素本身中拥有文本.

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.

假设您真的只想更新元素,我个人会使用 LINQ to XML 而不是 XmlDocument:

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");

如果你想更新所有Product元素,你应该用循环doc.Descendants("Product")foreach 循环.

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

这篇关于用c#增加一个xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆