简体   繁体   English

覆盖xml文件值

[英]Overwrite a xml file value

I have a xml file like this 我有一个这样的xml文件

<count>0</count>

Now I wish to overwrite the value 0. How do I do that in c#? 现在,我希望覆盖值0。如何在c#中做到这一点?

EDIT 编辑

<counter>
  <count>0</count>
  <email>
  </email>
</counter>`

This is my XML file I wish to write a value in the email element and also change the value of count element 这是我的XML文件,我希望在email元素中写入一个值,并更改count元素的值

            XmlDocument doc = new XmlDocument();
            doc.Load(COUNTER);
            foreach (XmlNode node in doc.SelectNodes("count"))
            {
                node.InnerText = (count-1).ToString();
            }
            foreach (XmlNode node in doc.SelectNodes("email"))
            {
                node.InnerText = (count - 1).ToString();
            }
            doc.Save(COUNTER); `

When I do this no values are written to the file 当我这样做时,没有值写入文件

You're not showing us the entire XML, so we cannot really tell you in detail how to do it. 您没有向我们展示整个XML,因此我们无法真正详细地告诉您如何做。

Basically, if your XML file is fairly small, you can load it into an XmlDocument and then search for that <child> node using an XPath expression, and then replace that node's value. 基本上,如果您的XML文件很小,则可以将其加载到XmlDocument ,然后使用XPath表达式搜索该<child>节点,然后替换该节点的值。

Something like: 就像是:

// create your XmlDocument
XmlDocument doc = new XmlDocument();

// load the XML from a file on disk - ADAPT to your situation!
doc.Load(@"C:\test.xml");

// search for a node <count>
XmlNode countNode = doc.SelectSingleNode("/counter/count");

// if node is found
if(countNode != null)
{
    // update the node's .InnerText value (the "contents" of the node)    
    countNode.InnerText = "42";

}

// search for a node <email>
XmlNode emailNode = doc.SelectSingleNode("/counter/email");

// if node is found
if(emailNode != null)
{
    // update the node's .InnerText value (the "contents" of the node)    
    emailNode.InnerText = "bob@microsoft.com";
}

// save XmlDocument out to disk again, with the change
doc.Save(@"C:\test_new.xml");

You can read the file in C# using C# XML Classes change the value and then write it back to the file. 您可以使用C#XML类在C#中读取文件,然后更改该值,然后将其写回到文件中。

You can use ReplaceChild Method for that. 您可以为此使用ReplaceChild方法

for more info read on XmlDocument and see this Microsoft Example 有关更多信息,请阅读XmlDocument并查看此Microsoft示例

Using Linq to Xml: 使用Linq转Xml:

XElement x = XElement.Parse("<myDocument><code>0</code></myDocument>");
x.Descendants().Where(n=>n.Name.LocalName.Equals("code")).ToList().ForEach(n=>n.SetValue("1"));

LINQPad is a great tool for experimenting with this. LINQPad是一个很好的实验工具。

您的直接问题是使用doc.SelectNodes("count")而不是doc.GetElementsByTagName("count")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM