2011-12-05 39 views
2

我正在爲我的應用程序使用WinForms .NET 2.0。以前,我使用.NET 4.0的元素以這種方式添加到現有的XML文件:C#如何將元素添加到xml文件

 XDocument doc = XDocument.Load(spath); 
     XElement root = new XElement("Snippet"); 
     root.Add(new XAttribute("name", name.Text)); 
     root.Add(new XElement("SnippetCode", code.Text)); 
     doc.Element("Snippets").Add(root); 
     doc.Save(spath); 

哪裏SPATH是XML文件的路徑。由於語法混亂,我無法將此代碼降級到.NET 2.0,有人可以幫助我嗎?我想用這樣的屬性和元素添加元素:

<Snippet name="snippet name"> 
    <SnippetCode> 
    code goes here 
    </SnippetCode> 
    </Snippet> 

回答

2

試試這個代碼:

XmlDocument doc = new XmlDocument(); 
doc.Load(spath); 
XmlNode snippet = doc.CreateNode(XmlNodeType.Element, "Snippet", null); 

XmlAttribute att = doc.CreateAttribute("name"); 
att.Value = name.Text; 
snippet.Attributes.Append(att); 

XmlNode snippetCode = doc.CreateNode(XmlNodeType.Element, "SnippetCode", null); 
snippetCode.InnerText = code.Text; 

snippet.AppendChild(snippetCode); 

doc.SelectSingleNode("//Snippets").AppendChild(snippet); 
+0

完美的作品。謝謝。 – david