xmlnode insertafter secondchild ...还是第三个?

时间:2012-05-03 23:54:00

标签: c# xml xmlnode css-selectors insertafter

我知道这可能看起来像一个愚蠢的问题,我试图检查msdn文档,并搜索这个网站一段时间。遗憾的是,我无法真正理解如何去做。

我想在第二个或第三个孩子之后插入一个节点。我的XML的主要内容在于它的孙子孙女,当我使用root.insert之后,我把它放在第一个孩子之后。

XML:

<myCourse>
  <courseName>BEng Mobile and Web Computing</courseName>
  <courseStructure>
    <module>
      <moduleTitle>Programming Methodology</moduleTitle>
      <credits>15</credits>
      <semester>1</semester>
    </module>
    <module>
      <moduleTitle>Computer Systems Fundamentals</moduleTitle>
      <credits>15</credits>
      <semester>1</semester>
    </module>
  </courseStructure>
</myCourse>

和代码:

    private void buttonCreateNode_Click(object sender, EventArgs e)
    {
        // Load the XML document.
        XmlDocument document = new XmlDocument();
        document.Load(@"temp.xml");

        // Get the root element.
        XmlElement root = document.DocumentElement;

        // Create the new nodes.
            XmlElement newModule = document.CreateElement("module");
            XmlElement newTitle = document.CreateElement("moduleTitle");
            XmlElement newCredits = document.CreateElement("credits");
            XmlElement newSemester = document.CreateElement("semester");
            XmlText title = document.CreateTextNode("ECA411");
            XmlText credits = document.CreateTextNode("15");
            XmlText semester = document.CreateTextNode("1");

            // Insert the elements.
            newBook.AppendChild(newTitle);
            newBook.AppendChild(newCredits);
            newBook.AppendChild(newSemester);
            newTitle.AppendChild(title);
            newCredits.AppendChild(credits);
            newSemester.AppendChild(semester);
            root.InsertAfter(newModule, root.LastChild);

        document.Save(@"temp.xml");

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

感谢您的帮助@Mikkelbu。

然而,我找到了解决我的问题的方法,我现在能够完成我想要实现的目标。

如下:

XmlNode parentNode = document.SelectSingleNode("myCourse/courseStructure/level4");
            parentNode.InsertBefore(newModule, parentNode.FirstChild);

答案 1 :(得分:0)

如果我理解您的问题是正确的,那么您希望在标题为Computer Systems Fundamentals的模块之后插入新模块。如果是这样,那么您需要更改插入的根目录。 所以你可以改变这一行

XmlElement root = document.DocumentElement;

XmlNode root = document.DocumentElement.LastChild;

我还会将变量名称root更改为例如courseStructureNode,并相应更正注释。

聚苯乙烯。要编译代码,您还需要将newBook更改为newModule