As I read an XML file using XmlTextReader, I sometimes need to save off a node, and it's children. I do this using XmlTextWriter (I'm not married to this approach).
The problem is XmlTextReader is aware of a bunch of namespaces that this fragment uses in the prefixes on nodes and attributes, but does not declare at that point is they were declared higher up (usually but not always in the root node).
I'm fine telling XmlTextWriter of all the namespaces even if some aren't used.
My first question is, how do I best copy the namespaces over? Do I call XmlTextReader.GetNamespacesInScope (what parameter)? and then one by one call XmlTextWriter.WriteAttributeString() to write each namespace?
And if I do it this way, is XmlTextWriter smart enough to know these are namespace declarations and therefore not re-write them again in child nodes?
Second, if I use XmlTextWriter.WriteAttributeString(localName, ns, value) for an additional namespace coming into scope on an inner node, is it smart enough to add those namespaces? Or do I need to explicitly add it using XmlTextWriter.WriteAttributeString(prefix, uri)?
Basic code:
// 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?
Yes, the solution is to copy over the namespaces from the reader by calling:
reader.GetNamespacesInScope (System.Xml.XmlNamespaceScope.ExcludeXml)
and adding in all the namespaces returned. Works great.