Search code examples
c#xmlxpathxmldocument

insert element after selected node


Am trying to add a new element called entity after the last entity but it keeps adding it inside the selected entity. To understand better this is my xml sample.

<Root>
  <Class Name="ECMInstruction" Style="Top">
    <Entity Id="1" Name="DocumentInformation" />
    <Entity Id="2" Name="CustomerInformation" />
    <Property Id="1" Name="DocumentTitle">
    </Property>
    <Property Id="2" Name="DateCreated">
      <Lists>
        <ListName>ws_Users</ListName>
        <ListName>dfdfdfd</ListName>
      </Lists>
    </Property>
    <Property Id="3" Name="Deadline">
    </Property>
  </Class>
</Root>

This is how it looks like after is inserted. I've tried using insertAfter but it gives me error.

<Entity Id="1" Name="DocumentInformation">
  <Entity Id="2" Name="sds" />
</Entity>

The code:

    XmlDocument xmldoc = new XmlDocument();
    xmldoc.Load("sample.xml");
    XmlNodeList cnode = xmldoc.DocumentElement.SelectNodes("//Class[@Name='" + CurrentClass + "']/Entity");
    foreach (XmlNode c in cnode)
    {
        int value = 0;
        String entitycount = cnode.Count.ToString();
        int.TryParse(entitycount, out value);
        value = value + 1;
        XmlElement root = xmldoc.CreateElement("Entity");
        root.SetAttribute("Id", value.ToString());
        root.SetAttribute("Name", EntityNametxt.Text);
        c.AppendChild(root);
        xmldoc.Save("sample.xml");
    }

Solution

  • "I've tried using insertAfter but it gives me error. "

    As per documentation, InsertAfter() should be called on parent node of referenced XmlNode (the 2nd argument of the method), otherwise ArgumentException will be thrown :

    //instead of this : c.AppendChild(root);
    //..you could do as follow :
    c.ParentNode.InsertAfter(root, c);