使用命名空间别名而不是XElement上的URI选择命名空间的XML节点属性

我正在尝试从严格命名的XML文档中查询一些信息,并且在查找也是命名空间的属性时遇到了一些麻烦。

XML看起来像:

        ...  

我的目标是创建一个包含国家/地区代码和国家/地区名称的对象列表。 这对我现在有用:

 XmlReader reader = XmlReader.Create(@"path/to/xml.xml"); XDocument root = XDocument.Load(reader); XmlNameTable nameTable = reader.NameTable; XmlNamespaceManager nsManager = new XmlNamespaceManager(nameTable); nsManager.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); nsManager.AddNamespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#"); nsManager.AddNamespace("skos", "http://www.w3.org/2004/02/skos/core#"); nsManager.AddNamespace("geo", "http://www.geonames.org/ontology#"); var geoCountries = from country in root.XPathSelectElements("./rdf:RDF/geo:Country", nsManager) select new { CountryCode = country.Attributes("{http://www.w3.org/2004/02/skos/core#}notation").First().Value, CountryName = country.Attributes("{http://www.w3.org/2000/01/rdf-schema#}label").First().Value }; 

这工作正常,但我想使用命名空间别名找到属性,而不是命名空间URI(只是因为),或者至少能够使用别名查找URI。 为了尝试后一种想法,我最终想通了我可以做到这一点:

 country.Attributes(nsManager.LookupNamespace("skos") + "notation").First().Value 

但是我得到一个XmlException :’:’字符,hex值0x3A,不能包含在名称中。

那么我试过了:

 country.Attributes("{" + nsManager.LookupNamespace("skos") + "}notation").First().Value 

然后它可以工作,但似乎可能或应该是一种更简单的方法,或者更确切地说, {namespace}attribute语法对我来说似乎很愚蠢,就像可能在框架中抽象出来的东西一样。

  • 所有这些,是否有任何快捷方式或更简单的方法来查找命名空间属性?

我很感激任何反馈。 谢谢!

使用Linq到xml

 XNamespace skos = XNamespace.Get("http://www.w3.org/2004/02/skos/core#"); XNamespace geo = XNamespace.Get("http://www.geonames.org/ontology#"); XNamespace rdfs = XNamespace.Get("http://www.w3.org/2000/01/rdf-schema#"); XDocument rdf = XDocument.Load(new StringReader(xmlstr)); foreach(var country in rdf.Descendants(geo + "Country")) { Console.WriteLine( country.Attribute(skos + "notation").Value + " " + country.Attribute(rdfs + "label").Value ); }