当我使用XmlTextReader读取XML文件时,有时需要保存一个节点及其子节点。我使用XmlTextWriter来做这件事(我不喜欢这种方法)。
问题是XmlTextReader知道这个片段在节点和属性的前缀中使用了一堆名称空间,但在这一点上没有声明它们是在更高的位置声明的(通常但不总是在根节点中)。
我可以告诉XmlTextWriter所有的名称空间,即使有些名称空间不被使用。
我的第一个问题是,如何最好地复制名称空间?要调用XmlTextReader.GetNamespacesInScope (什么参数)吗?然后一个接一个地调用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?
发布于 2018-06-03 05:02:02
是的,解决方案是通过调用以下命令从读取器复制名称空间:
reader.GetNamespacesInScope (System.Xml.XmlNamespaceScope.ExcludeXml)
并添加所有返回的名称空间。效果很好。
https://stackoverflow.com/questions/50659766
复制相似问题