如何在XML文档中使用c#添加一个新元素

问题描述 投票:0回答:1

我需要的是在一个已经存在的XML文档中添加一个新元素。这就是XML。

enter image description here

我需要的是在元素的结尾添加这个元素

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

预期结果

enter image description here

这是我创建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);

}
c# xml .net-core xmlserializer xpathnavigator
1个回答
3
投票

你可以添加这样的元素。

 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");
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.