【问题标题】:Adding a node in the beginning of XML parent node在 XML 父节点的开头添加一个节点
【发布时间】:2016-01-21 08:36:43
【问题描述】:

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

【问题讨论】:

  • 很不清楚你在问什么,或者你尝试了什么。如果您可以提供一个小例子来说明您正在尝试做的事情,并显示尝试实现它的代码,以及与您想要发生的事情相比发生了什么,那将真的很有帮助。如果可以的话,我还强烈建议使用 LINQ to XML,因为它是一种比 XmlDocument 更好的 XML API。

标签: c# .net xml xmlnode


【解决方案1】:

据我了解您的问题,您可能正在寻找XmlNode.PrependChild() 方法。
示例:

XmlDocument doc = new XmlDocument();
XmlNode root = doc.DocumentElement;

//Create a new node.
XmlElement node = doc.CreateElement("price");

//Add the node to the document.
root.PrependChild(node);

MSDN documentation

【讨论】:

    【解决方案2】:

    我相信问题是询问如何将节点添加到 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      相关资源
      最近更新 更多