Search code examples
c#xmlxmldocument

Not able to properly save changes to XML document when using "InsertAfter"


I am basically trying to add a node that I create after an existing node. Here, I have a list of the parent node (Tag) and a list of the child node (Name). I want to add the the node I created after the child node. I have stepped through each iteration and the correct changes are made each iteration but it does not save properly when going to the next iteration.

input.xml

<Tag><Name>NAME 1</Name></Tag>
<Tag><Name>NAME 2</Name></Tag>
<Tag><Name>NAME 3</Name></Tag>

output.xml

<Tag><Name>NAME 1</Name></Tag>
<Tag><Name>NAME 2</Name></Tag>
<Tag><Name>NAME 3</Name><Node>Node Inner Text</Node></Tag>

Goal

<Tag><Name>NAME 1</Name><Node>Node Inner Text</Node></Tag>
<Tag><Name>NAME 2</Name><Node>Node Inner Text</Node></Tag>
<Tag><Name>NAME 3</Name><Node>Node Inner Text</Node></Tag>

Code

XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
xmlDoc.Load("test.xml"); // Load the XML document from the specified file

XmlNodeList NameList = xmlDoc.SelectNodes("//Tag/Name");
XmlNodeList TagList = xmlDoc.SelectNodes("//Tag");

//create ---> <Node>Node Inner Text</Node>
XmlNode NodeToAdd = xmlDoc.CreateElement("Node");
NodeToAdd.InnerText = "Node Inner Text";

for (int i = 0; i < TagList.Count; i++)
{
    TagList[i].InsertAfter(NodeToAdd, NameList[i]);
}
xmlDoc.Save("output.xml");

Solution

  • The reason is that you are inserting same instance of created XmlNode.
    So InsertAfter method will move existed node from previous <Tag> node to next.

    You can create new node inside loop then you will get expected output

    for (int i = 0; i < TagList.Count; i++)
    {
        XmlNode NodeToAdd = xmlDoc.CreateElement("Node");
        NodeToAdd.InnerText = "Node Inner Text";
    
        TagList[i].InsertAfter(NodeToAdd, NameList[i]);
    }
    
    xmlDoc.Save("output.xml");