2009-02-04 158 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; 
} 
相關問題