在选定节点后插入元素

本文关键字:插入 元素 节点 | 更新日期: 2023-09-27 18:15:29

我试图在最后一个实体之后添加一个名为entity的新元素,但它不断将其添加到所选实体中。为了更好地理解,这是我的xml示例。

<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>

这是插入后的样子。我试过使用insertAfter,但它给了我错误。

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

代码:

    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");
    }

在选定节点后插入元素

"我已经尝试使用insertAfter,但它给我错误。"

根据文档,InsertAfter()应该在引用XmlNode的父节点上调用(方法的第二个参数),否则将抛出ArgumentException:

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