Copy Xml element to another document in C #

I have searched many places and seen many examples, but I still cannot add nodes to my XML in the places I want.

Here's my problem :

I have an XML file that my program will read to use as a template for my new XML file. But as I said, this "XML template" I created will only have the most general definitions, so that means I will need to read one specific node of this template, add it to a new xml, create new nodes and their to a new XML file

XML Template:

<A>
  <B>
    <c>element 1</c>
    <d>element 2</d>
    <e>element 3</e>
  </B>
  <B>
    <c>element 4</c>
    <d>element 5</d>
    <e>element 6</e>
  </B>
</A>

      

Here is the new file I need to create:

<A>
  <B>
    <c>element 7</c>
    <d>element 8</d>
    <e>element 9</e>
    <f>element 10</f>
    <g>element 11</g>
  </B>
<B>
    <c>element 12</c>
    <d>element 13</d>
    <e>element 14</e>
    <f>element 15</f>
    <g>element 16</g>
  </B>
</A>

      

As you can see the structure below

<A>
  <B>
    <c>element 7</c>
    <d>element 8</d>
    <e>element 9</e>
  </B>
</A>

      

I need to copy from my template xml to my new xml file (which node to select for the user), but this particular node will be copied to the new xml, then I will need to add some nodes in the node that I copied to the new file to make it more complete. I need to add them to B tags.

Once I was able to do this, I would need to allow the user to keep growing this new xml file by adding more template nodes and stacking them between the A tags.

I have already managed to copy the node xml template and add it to a new file, but I was unable to add new nodes and was unable to save this xml, every time I declare a B node to A node it signs the one that was previously.

If anyone knows how to help me, I would be very grateful as today was my first day using XML

+3


source to share


1 answer


I recommend using LINQ TO XML. I find it simple and straightforward to implement. here is an example how to read xml with LInq

   XDocument xmlDoc = XDocument.Load(Server.MapPath("XMLFile.xml"));

    var persons = (from elements in xmlDoc.Descendants("A")
    where elements.Element("c").Value==//VALUE YOU LOOKING TO GET 
    select new
    {
    c = elements.Element("c").Value,
    d = elements.Element("d").Value,
    e = elements.Element("e").Value,
    }).FirstOrDefault();
    /// ADD ELEMENT TO ANOTHER XML

      

XDocument xmlDoc = XDocument.Load (Server.MapPath ("AnotherXMLFile.xml"));



    xmlDoc.Element("A").Add(new XElement("B", new XElement("e", persons.e)));

      

and here is a very good tutorial

http://www.aspnettutorials.com/tutorials/xml/linq-to-xml-adding-cs.aspx

+2


source







All Articles