Darren Hoehna
Darren Hoehna

Reputation: 379

How to insert a child element into an existing element

I am using a XDocument to write an xml file and I am writing to the document in two different places. After the first write I have

<?xml version="1.0" encoding="utf-8"?>
<suspensedata connectionid="000" customerid="000" name="MyName" />

After the second write I want the file to look like this

<?xml version="1.0" encoding="utf-8"?>
<suspensedata connectionid="560" customerid="131" name="ImgTransfer2327">
  <transaction DocumentID="46" SuspenseID="7">
    <field id="LocationID">000000015000</field>
    <field id="AccountNumber">50000</field>
    <field id="AmountPaid">25.00</field>
    <field id="CheckAmount">100.00</field>
    <field id="CheckNo">000</field>
  </transaction>
</suspensedata>

But I can't seem to get the insert done correctly.

I've tried (The name of my XDocument is ValidXml) ValidXml.Root.Add(new Element("transaction")); and that does not change anything.

I have also tried ValidXml.Element("suspensedata").Add(new XElement("transaction")); But that did not work either.

How would I add this child element?

EDIT: Both attempts did not produce any other output besides the output on the first try. Also I did make sure to use ValidXml.Save()

Upvotes: 0

Views: 115

Answers (1)

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13755

I have tried something like this I supposed that the two parts are in 2 files

//xmlfile1 contains the first part

  <?xml version="1.0" encoding="utf-8"?>
  <suspensedata connectionid="000" customerid="000" name="MyName" />

//this part will be loaded like this

  XDocument xDoc = XDocument.Load("xmlfile1.xml");
       XElement elt = xDoc.Root;  

//and the second file contains the second part

         XDocument xDoc2 = XDocument.Load("xmlfile2.xml");
         XElement elt2 = xDoc2.Root;
         elt.Add(elt2);
         xDoc.Save("xmlfile1.xml");  

Hope this help

Upvotes: 1

Related Questions