【发布时间】:2011-09-15 17:25:20
【问题描述】:
我正在使用XmlReader 遍历一个大型 XML 文档,并将其拼接成一个更小且更易于管理的XmlDocmuent。在此过程中,我发现了一个有趣的节点,因此我要移动它:
targetDoc.LoadXml("<result></result>");
// Some interesting code removed
using (XmlReader r = XmlReader.Create(file))
{
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
{
if (r.Name == match)
{
// Put the node into the target document
targetDoc.FirstChild.InnerXml = r.ReadOuterXml();
return targetDoc;
}
}
}
}
这一切都很好,除了我想包含节点没有它的后代。我感兴趣的是节点本身及其属性。在这一点上,后代非常大,笨重且无趣。 (并且一次将它们全部读入内存会导致内存不足错误......)
是否有一种简单的方法可以将找到的元素的文本 (?) 及其属性(而不是其后代)获取到目标文档中?
【问题讨论】:
-
你不应该使用
new XmlTextReader()。请改用XmlReader.Create()。 -
它实际上是作为来自外部函数(未显示)的参数传递并为 SO 键入的。编辑所以希望我会得到一个有用的答案。
-
试图帮助那些不知道比复制/粘贴他们在此处看到的代码更好的人。