如何向XML追加内容

4
我有这个 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 可以让你编辑文本。 - Daniel Mann
你有没有查看过 AppendChild?http://msdn.microsoft.com/zh-cn/library/system.xml.xmlnode.appendchild.aspx - WorldIsRound
3个回答

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片段在哪里 - 是在文件/字符串中吗?

虽然不是最简单的方法,但我喜欢看到XmlDocument仍在发挥作用,+1 - Adrian Iftode

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接