2012-03-03 99 views
4

我有這個xml。如何追加到xml

<project> 
    <user> 
     <id>1</id> 
     <name>a</name> 
    </user> 
    <user> 
     <id>2</id> 
     <name>b</name> 
    </user> 
</project> 

現在怎麼可以追加一個新元素這樣的元素<project></project>

<user> 
    <id>3</id> 
    <name>c</name> 
</user> 
+1

的Notepad.exe,您可以編輯文本 – 2012-03-03 23:48:30

+0

你到那到AppendChild中? http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.appendchild.aspx – WorldIsRound 2012-03-03 23:50:30

回答

6
string xml = 
    @"<project> 
     <user> 
      <id>1</id> 
      <name>a</name> 
     </user> 
     <user> 
      <id>2</id> 
      <name>b</name> 
     </user> 
    </project>"; 

XElement x = XElement.Load(new StringReader(xml)); 
x.Add(new XElement("user", new XElement("id",3),new XElement("name","c"))); 
string newXml = x.ToString(); 
3

之間。如果你的意思是用C#則可能是最簡單的方法就是了加載XML到XmlDocument對象,然後添加一個表示附加元素的節點。

例如類似於:

string filePath = "original.xml"; 

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.Load(filePath); 
XmlElement root = xmlDoc.DocumentElement; 

XmlNode nodeToAdd = doc.CreateElement(XmlNodeType.Element, "user", null); 
XmlNode idNode = doc.CreateElement(XmlNodeType.Element, "id", null); 
idNode.InnerText = "1"; 
XmlNode nameNode = doc.CreateElement(XmlNodeType.Element, "name", null); 
nameNode.InnerText = "a"; 

nodeToAdd.AppendChild(idNode); 
nodeToAdd.AppendChild(nameNode); 


root.AppendChild(nodeToAdd); 

xmlDoc.Save(filePath); // Overwrite or replace with new file name 

但是你沒有說過xml片段在哪裏 - 在文件/字符串中?

+0

實際上並不是最簡單的方法,但我喜歡看到XmlDocument仍然在行動,+1 – 2012-03-04 00:33:43

1

如果您有以下XML文件:

<CATALOG> 
    <CD> 
    <TITLE> ... </TITLE> 
    <ARTIST> ... </ARTIST> 
    <YEAR> ... </YEAR> 
    </CD> 
</CATALOG> 

,你得再添<CD>節點及其所有子節點:

using System.Xml; //use the xml library in C# 
XmlDocument document = new XmlDocument(); //creating XML document 
document.Load(@"pathOfXmlFile"); //load the xml file contents into the newly created document 
XmlNode root = document.DocumentElement; //points to the root element (catalog) 
XmlElement cd = document.CreateElement("CD"); // create a new node (CD) 

XmlElement title = document.CreateElement("TITLE"); 
title.InnerXML = " ... "; //fill-in the title value 
cd.AppendChild(title); // append title to cd 
XmlElement artist = document.CreateElement("ARTIST"); 
artist.InnerXML = " ... "; 
cd.AppendChild(artist); 
XmlElement year = document.CreateElement("YEAR"); 
year.InnerXML = " ... "; 
cd.AppendChild(year); 

root.AppendChild(cd); // append cd to the root (catalog) 

document.save(@"savePath");//save the document