C# 在XML父节点的开头添加节点

C# 在XML父节点的开头添加节点,c#,.net,xml,xmlnode,C#,.net,Xml,Xmlnode,我想在父节点中添加一个xmlNode,但在顶部/开头。我可以使用XMLNode.AppendChild()的变体吗?据我所知,您可能正在寻找XMLNode.PrependChild()方法。 例如: 据我所知,您可能正在寻找XmlNode.PrependChild()方法。 例如: 我认为问题在于如何将节点添加到XML文件的开头。我是这样做的: // This is the main xml document XmlDocument document = new XmlDocument();

我想在父节点中添加一个xmlNode,但在顶部/开头。我可以使用
XMLNode.AppendChild()
的变体吗?

据我所知,您可能正在寻找
XMLNode.PrependChild()
方法。
例如:


据我所知,您可能正在寻找
XmlNode.PrependChild()
方法。
例如:


我认为问题在于如何将节点添加到XML文件的开头。我是这样做的:

// This is the main xml document
XmlDocument document = new XmlDocument();

// This part is creation of RootNode, however you want
XmlNode RootNode = document.CreateElement("Comments");
document.AppendChild(RootNode);

//Adding first child node as usual
XmlNode CommentNode1 = document.CreateElement("UserComment");
RootNode.AppendChild(commentNode1);

//Now create a child node and add it to the beginning of the XML file
XmlNode CommentNode2 = document.CreateElement("UserComment");
RootNode.InsertBefore(commentNode2, RootNode.FirstChild);

我认为问题在于如何将节点添加到XML文件的开头。我是这样做的:

// This is the main xml document
XmlDocument document = new XmlDocument();

// This part is creation of RootNode, however you want
XmlNode RootNode = document.CreateElement("Comments");
document.AppendChild(RootNode);

//Adding first child node as usual
XmlNode CommentNode1 = document.CreateElement("UserComment");
RootNode.AppendChild(commentNode1);

//Now create a child node and add it to the beginning of the XML file
XmlNode CommentNode2 = document.CreateElement("UserComment");
RootNode.InsertBefore(commentNode2, RootNode.FirstChild);

很不清楚你在问什么,或者你试过什么。如果您能提供一个小示例,说明您正在尝试做什么,并展示尝试实现它的代码,以及与您希望发生的事情相比发生了什么,这将非常有帮助。如果可能的话,我还强烈建议使用LINQ to XML,因为它是一种比
XmlDocument
好得多的XML API。如果您能提供一个小示例,说明您正在尝试做什么,并展示尝试实现它的代码,以及与您希望发生的事情相比发生了什么,这将非常有帮助。如果可能的话,我还强烈建议使用LINQtoXML,因为它是比
XmlDocument
更好的XML API。