[英]Overwrite a xml file value
我有一个这样的xml文件
<count>0</count>
现在,我希望覆盖值0。如何在c#中做到这一点?
编辑
<counter>
<count>0</count>
<email>
</email>
</counter>`
这是我的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); `
当我这样做时,没有值写入文件
您没有向我们展示整个XML,因此我们无法真正详细地告诉您如何做。
基本上,如果您的XML文件很小,则可以将其加载到XmlDocument
,然后使用XPath表达式搜索该<child>
节点,然后替换该节点的值。
就像是:
// 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");
使用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是一个很好的实验工具。
您的直接问题是使用doc.SelectNodes("count")
而不是doc.GetElementsByTagName("count")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.