1

このようなxmlファイルがあります

<count>0</count>

ここで、値 0 を上書きしたいと思います。C# でそれを行うにはどうすればよいですか?

編集

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

これは、email 要素に値を書き込み、count 要素の値も変更したい XML ファイルです。

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

これを行うと、値はファイルに書き込まれません

4

4 に答える 4

3

XML 全体を示しているわけではないので、その方法を詳しく説明することはできません。

基本的に、XML ファイルがかなり小さい場合は、XML ファイルを にロードし、XPath 式を使用XmlDocumentしてそのノードを検索し、<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");
于 2011-02-09T17:31:04.010 に答える
1

C#XMLクラスを使用してC#でファイルを読み取り、値を変更してからファイルに書き戻すことができます。

そのためにReplaceChildメソッドを使用できます。

詳細については、XmlDocumentを読み、このMicrosoftの例を参照してください。

于 2011-02-09T17:04:43.543 に答える
1

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は、これを試すための優れたツールです。

于 2011-02-09T17:59:42.870 に答える
0

あなたの直接の問題は、のdoc.SelectNodes("count")代わりにの使用ですdoc.GetElementsByTagName("count")

于 2011-02-09T18:15:49.367 に答える