简体   繁体   English

将xml文档附加到C#中的xml节点?

[英]Append an xml document to an xml node in C#?

如何将XML文档附加到c#中的xml节点?

An XmlDocument is basically an XmlNode , so you can append it just like you would do for any other XmlNode . 一个XmlDocument基本上一个XmlNode ,所以你可以添加它,就像你会为任何其他做XmlNode However, the difference arises from the fact that this XmlNode does not belong to the target document, therefore you will need to use the ImportNode method and then perform the append. 但是,不同之处在于此 XmlNode不属于目标文档,因此您需要使用ImportNode方法然后执行追加。

// xImportDoc is the XmlDocument to be imported.
// xTargetNode is the XmlNode into which the import is to be done.

XmlNode xChildNode = xSrcNode.ImportNode(xImportDoc, true);
xTargetNode.AppendChild(xChildNode);

Yes: 是:

XmlNode imported = targetNode.OwnerDocument.ImportNode(otherDocument.DocumentElement, true);
targetNode.AppendChild(imported);

I think this creates a clone of your document though. 我认为这会创建一个文档的克隆。

Let's say you have the following construction: 假设你有以下结构:

The following structure is stored in an XmlElement named xmlElement: 以下结构存储在名为xmlElement的XmlElement中:

</root>

and the following structure is stored in an XmlNode object named FooNode; 并且以下结构存储在名为FooNode的XmlNode对象中;

<foo>
    <bar>This is a test</bar>
    <baz>And this is another test</baz>
</foo>

Then you do the following: 然后执行以下操作:

XmlNode node = doc.ImportNode(FooNode.SelectSingleNode("foo"), true);
xmlElement.AppendChild(node);

Hope it helps someone 希望它可以帮助某人

Perhaps like this: 也许是这样的:

XmlNode node = ......  // belongs to targetDoc (XmlDocument)

node.AppendChild(targetDoc.ImportNode(xmlDoc.DocumentElement));

Marc

Once you have the root node of the XML document in question you can append it as a child node of the node in question. 获得有问题的XML文档的根节点后,可以将其作为相关节点的子节点附加。 Does that make sense? 那有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM