C# 使用XmlTextWriter从XmlTextReader复制片段

C# 使用XmlTextWriter从XmlTextReader复制片段,c#,xml,xmltextreader,xmltextwriter,C#,Xml,Xmltextreader,Xmltextwriter,当我使用XmlTextReader读取XML文件时,有时需要保存节点及其子节点。我使用XmlTextWriter来实现这一点(我不喜欢这种方法) 问题是XmlTextReader知道这个片段在节点和属性的前缀中使用了一堆名称空间,但没有声明它们是向上声明的(通常但不总是在根节点中) 我可以告诉XmlTextWriter所有的名称空间,即使有些名称空间没有被使用 我的第一个问题是,如何最好地复制名称空间?我是否调用XmlTextReader.GetNamespacesScope(什么参数)?然后逐

当我使用XmlTextReader读取XML文件时,有时需要保存节点及其子节点。我使用XmlTextWriter来实现这一点(我不喜欢这种方法)

问题是XmlTextReader知道这个片段在节点和属性的前缀中使用了一堆名称空间,但没有声明它们是向上声明的(通常但不总是在根节点中)

我可以告诉XmlTextWriter所有的名称空间,即使有些名称空间没有被使用

我的第一个问题是,如何最好地复制名称空间?我是否调用XmlTextReader.GetNamespacesScope(什么参数)?然后逐个调用XmlTextWriter.WriteAttributeString()来编写每个命名空间

如果我这样做,XmlTextWriter是否足够聪明,能够知道这些是名称空间声明,因此不会在子节点中重新编写它们

其次,如果我使用XmlTextWriter.WriteAttributeString(localName,ns,value)作为进入内部节点作用域的附加名称空间,添加这些名称空间是否足够智能?或者我需要使用XmlTextWriter.WriteAttributeString(前缀,uri)显式添加它吗

基本代码:

// this object is created, is reading XML, and hit a point below eventually...
XmlTextReader reader;

// ...

// On handling a specific XmlNodeType.Element
MemoryStream stream = new MemoryStream();
XmlTextWriter fragment = new XmlTextWriter(stream, utf8);
// What do I do here to get the namespaces in scope in reader into writer?

是的,解决方案是通过调用以下命令从读取器复制名称空间:

reader.GetNamespacesInScope (System.Xml.XmlNamespaceScope.ExcludeXml)

并添加返回的所有名称空间。非常好。

为什么您要解释您的案例,而不是发布一些特定的xml示例和您尝试过的代码?为了让我们帮助您,请分享一个示例。从
XmlReader
XmlTextReader
的基类)复制到
XmlWriter
)已经有了一种方法,您正在使用它吗?另外,请注意,根据它们的文档,和被弃用,它们建议使用它们基类的制造实例。@dbc-不幸的是WriteNode()不起作用,因为除了保存片段外,我还需要解析正在读取的节点。所以我一个接一个地处理它们,并使用XmlTextWriter将它们写入片段中。然后看到一个显示您的问题的示例将是非常棒的。