简体   繁体   中英

How to Add a new element in XML document using c#

What I need is to add a new element to an XML Document that already exists. This is the XML:

在此处输入图像描述

And what I need is to add this element to the end of the element

 <DATA>
    <UBL21>true</UBL21>
    <Partnership>
        <ID>900430556</ID>
        <TechKey>20c68c93ee595efaf227db3bc5d0e3416776bc487ec7058b9157c874eaa741a2</TechKey>
        <SetTestID>dsfgsdghfsdgfsdfg</SetTestID>
    </Partnership>
</DATA>

Expected result

在此处输入图像描述

This is the method with which I create the xml

public void guardar_nuevo_xml(InvoiceType df, string numero_factura)
{
    //Here start xml df is an object from which I serialize the xml
    XmlSerializer x = new XmlSerializer(df.GetType());
    //path for save new document
    string path = @"C:\Users\moralesm\source\repos\Pruebas_Nilo\Nilo\xml\Factura" + numero_factura + ".xml";
    //write the new xml
    TextWriter writer = new StreamWriter(path);
    // the new xml is serialized with an object
    x.Serialize(writer, df);

}

You can add element like this:

 XDocument doc1 = XDocument.Load("Your Xml Path"); 
 XElement dataElement = new XElement("DATA");
 doc1.Root.Add(dataElement);
 dataElement.Add(new XElement("UBL21", "true"));
 XElement partnerShipElement = new XElement("Partnership");
 dataElement.Add(partnerShipElement); 
 partnerShipElement.Add(new XElement("ID", "900430556"));
 partnerShipElement.Add(new XElement("TechKey", "20c68c93ee595efaf227db3bc5d0e3416776bc487ec7058b9157c874eaa741a2"));
 partnerShipElement.Add(new XElement("SetTestID", "dsfgsdghfsdgfsdfg"));

My Test Xml:

<test>
  <name>Hidayet</name>
</test> 

New Xml:

<test>
  <name>Hidayet</name>
  <DATA>
    <UBL21>true</UBL21>
    <Partnership>
      <ID>900430556</ID>
      <TechKey>20c68c93ee595efaf227db3bc5d0e3416776bc487ec7058b9157c874eaa741a2
      </TechKey>
      <SetTestID>dsfgsdghfsdgfsdfg</SetTestID>
    </Partnership>
  </DATA>
</test>

Save new xml file:

doc1.Save("New Xml File Path");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM