C# xmlnode insertafter secondchild…还是第三个?
我知道这似乎是一个愚蠢的问题,我已经尝试检查msdn文档并搜索这个网站一段时间了。不幸的是,我无法真正理解如何去做 我想在第二个或第三个子节点之后插入一个节点。我的XML的主要内容在它的子代中,当我使用root.inserta之后,我将它放在第一个孩子的后面 XML:C# xmlnode insertafter secondchild…还是第三个?,c#,xml,xmlnode,css-selectors,insertafter,C#,Xml,Xmlnode,Css Selectors,Insertafter,我知道这似乎是一个愚蠢的问题,我已经尝试检查msdn文档并搜索这个网站一段时间了。不幸的是,我无法真正理解如何去做 我想在第二个或第三个子节点之后插入一个节点。我的XML的主要内容在它的子代中,当我使用root.inserta之后,我将它放在第一个孩子的后面 XML: <myCourse> <courseName>BEng Mobile and Web Computing</courseName> <courseStructure>
<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");
非常感谢您的帮助。如果我理解您的问题是正确的,那么您希望在标题为《计算机系统基础》的模块后插入新模块。如果是这样,则需要更改插入的根。 所以你可以换线
XmlElement root = document.DocumentElement;
到
我还将变量名root
更改为例如courseStructureNode
,并相应地更正注释
注:要编译代码,您还需要将
newBook
更改为newModule
如果我理解您的问题是正确的,那么您需要在标题为计算机系统基础知识的模块后插入新模块。如果是这样,则需要更改插入的根。
所以你可以换线
XmlElement root = document.DocumentElement;
到
我还将变量名root
更改为例如courseStructureNode
,并相应地更正注释
注:要编译代码,您还需要将newBook
更改为newModule
谢谢您的帮助@Mikkelbu
然而,我已经找到了解决我的问题的办法,我现在能够实现我试图实现的目标
详情如下:
XmlNode parentNode = document.SelectSingleNode("myCourse/courseStructure/level4");
parentNode.InsertBefore(newModule, parentNode.FirstChild);
谢谢你的帮助@Mikkelbu
然而,我已经找到了解决我的问题的办法,我现在能够实现我试图实现的目标
详情如下:
XmlNode parentNode = document.SelectSingleNode("myCourse/courseStructure/level4");
parentNode.InsertBefore(newModule, parentNode.FirstChild);