private XmlParserContext GetContext(XmlNode node)
{
String lang = null;
XmlSpace spaceMode = XmlSpace.None;
XmlDocumentType docType = _doc.DocumentType;
String baseURI = _doc.BaseURI;
//constructing xmlnamespace
HashSet<string> prefixes = new HashSet<string>();
XmlNameTable nt = _doc.NameTable;
XmlNamespaceManager mgr = new XmlNamespaceManager(nt);
bool bHasDefXmlnsAttr = false;
// Process all xmlns, xmlns:prefix, xml:space and xml:lang attributes
while (node != null && node != _doc)
{
XmlElement element = node as XmlElement;
if (element != null && element.HasAttributes)
{
mgr.PushScope();
foreach (XmlAttribute attr in element.Attributes)
{
if (attr.Prefix == _doc.strXmlns && !prefixes.Contains(attr.LocalName))
{
// Make sure the next time we will not add this prefix
prefixes.Add(attr.LocalName);
mgr.AddNamespace(attr.LocalName, attr.Value);
}
else if (!bHasDefXmlnsAttr && attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns)
{
// Save the case xmlns="..." where xmlns is the LocalName
mgr.AddNamespace(String.Empty, attr.Value);
bHasDefXmlnsAttr = true;
}
else if (spaceMode == XmlSpace.None && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strSpace)
{
// Save xml:space context
if (attr.Value == "default")
spaceMode = XmlSpace.Default;
else if (attr.Value == "preserve")
spaceMode = XmlSpace.Preserve;
}
else if (lang == null && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strLang)
{
// Save xml:lag context
lang = attr.Value;
}
}
}
node = node.ParentNode;
}
return new XmlParserContext(
nt,
mgr,
(docType == null) ? null : docType.Name,
(docType == null) ? null : docType.PublicId,
(docType == null) ? null : docType.SystemId,
(docType == null) ? null : docType.InternalSubset,
baseURI,
lang,
spaceMode
);
}