Amila Iddamalgoda
Amila Iddamalgoda

Reputation: 4296

How to append data to existing xml?

I have this xml file called "list.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>

How can I append following data to the above 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>

Is this the correct way?

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);

Upvotes: 0

Views: 85

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101721

You can use 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);

See the documentation for more details: XContainer.Add Method

Upvotes: 2

Related Questions