当前位置: 首页 > 编程语言 > C#

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

时间:2023-04-10 23:25:48 C#

XML看起来像:...我的目标是创建一个包含国家代码和国家名称的对象列表。这现在对我有用:XmlReaderreader=XmlReader.Create(@"path/to/xml.xml");XDocumentroot=XDocument.Load(阅读器);XmlNameTablenameTable=reader.NameTable;XmlNamespaceManagernsManager=newXmlNamespaceManager(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#");vargeoCountries=来自根目录中的国家。XPathSelectElements("./rdf:RDF/geo:Country",nsManager)选择新的{CountryCode=country.属性("{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。为了尝试后一个想法,我终于发现我可以这样做:十六进制值0x3A,不能包含在名称中。然后我尝试了:country.Attributes("{"+nsManager.LookupNamespace("skos")+"}notation").First().Value并且它有效,但似乎可能或应该有一个更简单的方法,或者更确切地说,{namespace}attribute语法对我来说似乎很愚蠢,就像可能在框架中抽象出来的东西一样。我感谢任何反馈。谢谢!使用Linqtoxml以上是C#学习教程:使用命名空间别名而不是XElement上的URI来选择命名空间的XML节点属性。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注—XNamespaceskos=XNamespace.Get("http://www.w3.org/2004/02/skos/core#");XNamespacegeo=XNamespace.Get("http://www.geonames.org/ontology#");XNamespacerdfs=XNamespace.Get("http://www.w3.org/2000/01/rdf-schema#");XDocumentrdf=XDocument.Load(newStringReader(xmlstr));foreach(varcountryinrdf.Descendants(geo+"Country")){Console.WriteLine(country.Attribute(skos+"notation").Value+""+country.Attribute(rdfs+"label").Value)};}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: