How to add new element below existing element using xml Document

前端 未结 3 1332
生来不讨喜
生来不讨喜 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(@"Non-Fuel0");
    
    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);
    

提交回复
热议问题