2012-01-26 2 views
0

を使用してディスク上のXMLファイルを更新し、私は1よく知られたノードを持つXMLファイルを持って、Fooのそれを呼び出します。どのようにC#の

私は次のようになりますframgment持っているので、どこかのXMLファイル内:私はそれを変更したい

<Foo atr1="value1"/> 

<Foo atr1="value1"/> 
<MyElement .......> 
    <MoreMystuff> 
    </MoreMystuff> 
</MyElement> 

し、それがに書き戻される必要があるがディスク上の同じファイル

は何これを行うには良いと簡単な方法だろうか?

答えて

0

私はあなたのコードが

 XmlDocument doc = new XmlDocument(); 
     doc.LoadXml("<root><Foo atr1=\"value1\"/></root>"); 
     /// or load from file as you want 
     //doc.Load("pathTOfile.xml") 

     XmlElement root = doc.DocumentElement; 


     XmlElement elem = doc.CreateElement("MyElement"); 
     elem.Attributes.Append(doc.CreateAttribute("atrib")); 
     // Change the value of the first attribute. 
     elem.SetAttribute("atrib", "val"); 
     XmlElement MoreStyffElem = doc.CreateElement("MoreStuff"); 
     elem.AppendChild(MoreStyffElem); 

     doc.FirstChild.AppendChild(elem); 
     Console.WriteLine("Display the modified XML..."); 
     Console.WriteLine(doc.InnerXml); 
     //or save to file 
     //doc.Save("theSameFileName.xml") 

あるので、またこのリンクはあなた http://msdn.microsoft.com/en-en/library/y3y47afh.aspx

のために便利である必要がありますのみ1つのルート要素が存在することができたXMLスタンダールに応じて間違えていない場合