Overwrite a xml file value

回眸只為那壹抹淺笑 提交于 2020-01-16 05:31:10

问题


I have a xml file like this

<count>0</count>

Now I wish to overwrite the value 0. How do I do that in 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

            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


回答1:


Your direct problem is the use of doc.SelectNodes("count") instead of doc.GetElementsByTagName("count")




回答2:


You're not showing us the entire XML, so we cannot really tell you in detail how to do it.

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.

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



回答3:


You can read the file in C# using C# XML Classes change the value and then write it back to the file.

You can use ReplaceChild Method for that.

for more info read on XmlDocument and see this Microsoft Example




回答4:


Using Linq to 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.



来源:https://stackoverflow.com/questions/4948027/overwrite-a-xml-file-value

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