Question

Specifically (taking a deep breath): How would you go about finding all the XML name spaces within a C#/.NET XmlDocument for which there are no applicable schemas in the instance's XmlSchemaSet (Schemas property)?

My XPath magic is lacking the sophistication to do something like this, but I will keep looking in the meantime ...

Was it helpful?

Solution

You need to get a list of all the distinct namespaces in the document, and then compare that with the distinct namespaces in the schema set.

But namespace declaration names are typically not exposed in the XPath document model. But given a node you can get its namespace:

// Match every element and attribute in the document
var allNodes = xmlDoc.SelectNodes("//(*|@*)");
var found = new Dictionary<String, bool>(); // Want a Set<string> really
foreach (XmlNode n in allNodes) {
  found[n.NamespaceURI] = true;
}
var allNamespaces = found.Keys.OrderBy(s => s);

OTHER TIPS

The easiest way I've ever found to retrieve all of the namespaces from a given XmlDocument is to XPath through all the nodes finding unique Prefix and NamespaceURI values.

I've got a helper routine that I use to return these unique values in an XmlNamespaceManager to make life simpler when I'm dealing with complex Xml documents.

The code is as follows:

private static XmlNamespaceManager PrepopulateNamespaces( XmlDocument document )
{
    XmlNamespaceManager result = new XmlNamespaceManager( document.NameTable );
    var namespaces = ( from XmlNode n in document.SelectNodes( "//*|@*" )
                       where n.NamespaceURI != string.Empty
                       select new
                       {
                           Prefix = n.Prefix,
                           Namespace = n.NamespaceURI
                       } ).Distinct();

    foreach ( var item in namespaces )
        result.AddNamespace( item.Prefix, item.Namespace );

    return result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top