Reputation: 11
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);
}
Upvotes: 1
Views: 422
Reputation: 384
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");
Upvotes: 0