【问题标题】:Add XmlDocument as child node to another XmlDocument将 XmlDocument 作为子节点添加到另一个 XmlDocument
【发布时间】:2018-08-17 07:35:11
【问题描述】:

我有两个 XmlDocument,一个是根,另一个包含子级。我想将它们组合起来并将它们保存到一个文档中。目前我有这个:

XmlDocument root = new XmlDocument();
root.LoadXml("<tables><table></table></tables>");

XmlDocument childItem = new XmlDocument();                  
childItem.LoadXml(string.Format(@"<item>
 <column columnName=""Article_text"">{0}</column>
 <column columnName=""Article_name"">{1}</column>
 </item>", atext, aname));

 root.AppendChild(childItem);

我希望我的新文档的结构是表格/表格/项目。但是,上面的代码给我一个错误:

指定的节点不能作为该节点的有效子节点插入,因为指定的节点类型错误。

【问题讨论】:

    标签: c# xml xmldocument


    【解决方案1】:
    var newNode = root.ImportNode(childItem.FirstChild, true);
    root["tables"]["table"].AppendChild(newNode);
    

    首先将您的 item 元素导入到 root 文档中。期望 item 是您的根节点,您可以使用 FirstChildImportNode 来获取它:

     var newNode = root.ImportNode(childItem.FirstChild, true);
    

    并将其附加到您的 table 元素中:

    root["tables"]["table"].AppendChild(newNode);
    

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2015-10-22
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多