将 xml 文档附加到 C# 中的 xml 节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/635450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append an xml document to an xml node in C#?
提问by kjv
How can I append an XML document to an xml node in c#?
如何将 XML 文档附加到 c# 中的 xml 节点?
采纳答案by Cerebrus
An XmlDocument
isbasically an XmlNode
, so you can append it just like you would do for any other XmlNode
. However, the difference arises from the fact that thisXmlNode
does not belong to the target document, therefore you will need to use the ImportNode method and thenperform the append.
一个XmlDocument
是基本的XmlNode
,所以你可以添加它,就像你会为任何其他做XmlNode
。然而,不同点是事实,这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);
回答by marc_s
Perhaps like this:
也许像这样:
XmlNode node = ...... // belongs to targetDoc (XmlDocument)
node.AppendChild(targetDoc.ImportNode(xmlDoc.DocumentElement));
Marc
马克
回答by Grzenio
Yes:
是的:
XmlNode imported = targetNode.OwnerDocument.ImportNode(otherDocument.DocumentElement, true);
targetNode.AppendChild(imported);
I think this creates a clone of your document though.
我认为这会创建您文档的克隆。
回答by Gregory A Beamer
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. Does that make sense?
一旦获得了相关 XML 文档的根节点,您就可以将其作为相关节点的子节点进行附加。那有意义吗?
回答by Trond
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
希望它可以帮助某人