2

I've searched many places and seen many examples, but I'm still unable to add nodes to my XML in the places that I want.

Here's my problem:

I have an XML file, which will be read by my program, for the purpose of using it as a template for my new XML file. But as I've said, that "XML template" that I've created will only have the most general definitions, so that means that I'll need to read one especific node of that template, add it to the new xml, create new nodes and them to the new xml file

Template XML:

<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's the new file that 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 choose is up to the user), but that specific node will be copied to the new xml, then I will need to add some nodes to the node that I've copied to the new file to make it more complete. I'll need to add them to the B tags.

After I've been able to do that I will need to let the user keep growing that new xml file, by adding more template nodes and stacking them between the A tags.

I've already succeeded in copying the xml template node and adding it to the new file, but I haven't been able to add new nodes, nor have I been able to keep that xml growing, everytime I ad a B node to the A node it subscribes the one before.

If anyone knows how to help me I'd be very grateful, since today was my first day using XML

Spencer
  • 375
  • 1
  • 5
  • 17
morcillo
  • 1,091
  • 5
  • 19
  • 51
  • It's unclear to me what exactly are you asking. Could you show us relevant parts of your code and describe what exactly do you want it to do and what it actually does? – svick Mar 08 '12 at 02:15

1 Answers1

3

I recomend using LINQ TO XML I think it simple and easy to implement . here is the exampple 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

COLD TOLD
  • 13,513
  • 3
  • 35
  • 52