在所选节点后插入元素

时间:2014-07-29 11:59:31

标签: c# xml xpath xmldocument

我试图在最后一个实体之后添加一个名为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");
    }

1 个答案:

答案 0 :(得分:0)

  

“我尝试过使用insertAfter,但它给了我错误。”

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

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