2009-02-04 72 views

回答

1

你需要获取文档中所有不同的命名空间的列表,然后比较即使用模式集中的不同名称空间。

但是名称空间声明名称通常不会在XPath文档模型中公开。但考虑到一个节点,你可以得到它的命名空间:通过寻找独特的前缀和的namespaceURI值的所有节点

// 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); 
3

我曾经发现检索所有从给定的XmlDocument命名空间的最简单方法是XPath的。

我有一个帮助程序,用于在XmlNamespaceManager中返回这些唯一值,以便在处理复杂的Xml文档时使生活更简单。

的代码如下:

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; 
} 
相关问题