具體(深呼吸):如何找到在實例的XmlSchemaSet
(Schemas
屬性)中沒有適用模式的C#/。NET XmlDocument
中的所有XML名稱空間?如何在文檔中找到未知的XML名稱空間?
我的XPath神奇的是缺乏成熟到做這樣的事,但我會繼續尋找在此期間...
具體(深呼吸):如何找到在實例的XmlSchemaSet
(Schemas
屬性)中沒有適用模式的C#/。NET XmlDocument
中的所有XML名稱空間?如何在文檔中找到未知的XML名稱空間?
我的XPath神奇的是缺乏成熟到做這樣的事,但我會繼續尋找在此期間...
你需要獲取文檔中所有不同的命名空間的列表,然後比較即使用模式集中的不同名稱空間。
但是名稱空間聲明名稱通常不會在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);
我曾經發現檢索所有從給定的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;
}