如何将数据附加到现有的xml?

时间:2014-03-17 16:50:42

标签: c# xml

我有一个名为" list.xml"。

的xml文件
<?xml version="1.0" encoding="utf-8" ?>
<PeopleList>
<Person>
    <First-Name>John</First-Name>
    <Last-Name>Sims</Last-Name>
    <Address-1>214,NJ Lane</Address-1>
    <Address-2>Ney York</Address-2>
    <Post-Code>8000</Post-Code>
    <City>NJ</City>
</Person>
<Person>
    <First-Name>Arya</First-Name>
    <Last-Name>Stark</Last-Name>
    <Address-1>214,Latin Street</Address-1>
    <Address-2>Los Angeles</Address-2>
    <Post-Code>302</Post-Code>
    <City>CA</City>
</Person> 
<Person>
    <First-Name>Rick</First-Name>
    <Last-Name>Rider</Last-Name>
    <Address-1>500,LA Lane</Address-1>
    <Address-2>Miami</Address-2>
    <Post-Code>768</Post-Code>
    <City>LA</City>
</Person> 
</PeopleList>

如何追加以下数据到上面的xml?

<Person>
  <First-Name>Test User 1</First-Name>
  <Last-Name>Test Last Name</Last-Name>
  <Address-1>Test add 1</Address-1>
  <Address-2>Test add 2</Address-2>
  <Post-Code>Test Post code</Post-Code>
  <City>Test City</City>
</Person>

这是正确的方法吗?

XmlDocument xd = new XmlDocument();
xd.Load("list.xml");
XmlNode nl = xd.SelectSingleNode("//Person");
XmlDocument xd2 = new XmlDocument();
xd2.LoadXml("<Person><First-Name>20</First-Name>....</Person>");
XmlNode n = xd.ImportNode(xd2.FirstChild,true);
nl.AppendChild(n);

1 个答案:

答案 0 :(得分:2)

您可以使用LINQ to XML

 var newElement = new XElement("Person", 
            new XElement("First-Name", "Test User 1"),
            new XElement("Last-Name", "Test Last Name"),
            new XElement("Address-1", "Test add 1"),
            new XElement("Address-2", "Test add 2"),
            new XElement("Post-Code", "Test Post code"),
            new XElement("City", "Test City")
            );

 var xDoc = XDocument.Load("path");
 xDoc.Root.Add(newElement);
 xDoc.Save(path);

有关详细信息,请参阅文档:XContainer.Add Method