我需要的是在一个已经存在的XML文档中添加一个新元素。这就是XML。
我需要的是在元素的结尾添加这个元素
<DATA>
<UBL21>true</UBL21>
<Partnership>
<ID>900430556</ID>
<TechKey>20c68c93ee595efaf227db3bc5d0e3416776bc487ec7058b9157c874eaa741a2</TechKey>
<SetTestID>dsfgsdghfsdgfsdfg</SetTestID>
</Partnership>
</DATA>
预期结果
这是我创建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);
}
你可以添加这样的元素。
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>
保存新的xml文件。
doc1.Save("New Xml File Path");