How to add new element below existing element using xml Document

前端 未结 3 1321
生来不讨喜
生来不讨喜 2020-12-17 01:59

I have an element Name \"Dispute\" and want to add new element name \"Records\" below the element.
Eg: The current XML is in this format


         


        
相关标签:
3条回答
  • 2020-12-17 02:33

    InsertAfter must be called on the parent node (in your case "NonFuel").

    nonFuel.InsertAfter(xmlRecordNo, dispute);
    

    It may look a little confusing but it reads this way: you are asking the parent node (nonFuel) to add a new node (xmlRecordNo) after an existing one (dispute).

    A complete example is here:

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(@"<NonFuel><Desc>Non-Fuel</Desc><Description></Description><Quantity/><Amount/><Additional/><Dispute>0</Dispute></NonFuel>");
    
    XmlNode nonFuel = xmlDoc.SelectSingleNode("//NonFuel");
    XmlNode dispute = xmlDoc.SelectSingleNode("//Dispute");
    
    
    XmlNode xmlRecordNo=  xmlDoc.CreateNode(XmlNodeType.Element, "Records", null);
    xmlRecordNo.InnerText = Guid.NewGuid().ToString();
    nonFuel.InsertAfter(xmlRecordNo, dispute);
    
    0 讨论(0)
  • 2020-12-17 02:46

    Use 'AppendChild' method - to add as last element.

    0 讨论(0)
  • 2020-12-17 02:58
    XmlDocument doc = new XmlDocument();
    doc.Load("input.xml");
    
    XmlElement records = doc.CreateElement("Records");
    records.InnerText = Guid.NewGuid().ToString();
    doc.DocumentElement.AppendChild(records);
    
    doc.Save("output.xml"); // if you want to overwrite the input use doc.Save("input.xml");
    
    0 讨论(0)
提交回复
热议问题