簡體   English   中英

覆蓋xml文件值

[英]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");

您可以使用C#XML類在C#中讀取文件,然后更改該值,然后將其寫回到文件中。

您可以為此使用ReplaceChild方法

有關更多信息,請閱讀XmlDocument並查看此Microsoft示例

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM