0

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);
dcastro
  • 66,540
  • 21
  • 145
  • 155
Amila Iddamalgoda
  • 4,166
  • 11
  • 46
  • 85
  • What have you already tried? Does the system have the required permissions to write to the file? What problems are you actually experiencing? (see: [How to Ask](http://stackoverflow.com/questions/how-to-ask)) You might also find [this question](http://stackoverflow.com/questions/2645440/appending-an-existing-xml-file) helpful. – talegna Mar 17 '14 at 16:53
  • `Is this the correct way?` Why don't you try? If have tried it already what is the result? – L.B Mar 17 '14 at 16:54
  • the SelectSingleNode("//Person") will return allways the first person node and only this node. is that what you looking for? – knightsb Mar 17 '14 at 16:54

1 Answers1

2

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

Selman Genç
  • 100,147
  • 13
  • 119
  • 184