如何获得一个具有以下名称的元素?

我需要从这个XML获取CountryName: http ://api.hostip.info/?ip = 12.215.42.19

响应XML是:

 This is the Hostip Lookup Service hostip  inapplicable    12.215.42.19 Sugar Grove, IL UNITED STATES US     -88.4588,41.7696       

问题是我不能包括:Descendants方法中因为它抛出:

XmlException:’:’chracater,hex值0x3A,不能包含在名称中。

谢谢

试试这个

 var descendants = from i in XDocument.Load(xml).Descendants("Hostip") select i.Element("countryName"); 

更新

下载xml并找到countryName名称的完整代码

 string xml; using(var web = new WebClient()) { xml = web.DownloadString("http://api.hostip.info/?ip=12.215.42.19"); } var descendants = from i in XDocument.Parse(xml).Descendants("Hostip") select i.Element("countryName"); 

关于如何在LINQ to XML中应用名称空间的一个小例子:

 XElement doc = XElement.Load("test.xml"); XNamespace ns = "http://www.opengis.net/gml"; var firstName = doc.Descendants(ns + "name").First().Value; 

您需要引用gml命名空间; 一旦你完成了,你应该能够使用“gml:”右侧显示的标签名称进行导航

UPDATE

我不确定你应用这个的上下文,但这是一个有效的示例控制台应用程序:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace LinqToXmlSample { class Program { static void Main(string[] args) { XElement x = XElement.Load("http://api.hostip.info/?ip=12.215.42.19"); foreach (XElement hostip in x.Descendants("Hostip")) { string country = Convert.ToString(hostip.Element("countryName").Value); Console.WriteLine(country); } Console.ReadLine(); } } } 
 var gml = (XNamespace)"http://www.opengis.net/gml"; var doc = XDocument.Load(...) or XDocument.Parse(...); var name = doc.Descendants(gml + "featureMember").Descendants("countryName").First().Value; 

或者你可以去暴力破坏所有命名空间:

 void RemoveNamespace(XDocument xdoc) { foreach (XElement e in xdoc.Root.DescendantsAndSelf()) { if (e.Name.Namespace != XNamespace.None) { e.Name = XNamespace.None.GetName(e.Name.LocalName); } if (e.Attributes().Any(a => a.IsNamespaceDeclaration || a.Name.Namespace != XNamespace.None)) { e.ReplaceAttributes(e.Attributes().Select(a => a.IsNamespaceDeclaration ? null : a.Name.Namespace != XNamespace.None ? new XAttribute(XNamespace.None.GetName(a.Name.LocalName), a.Value) : a)); } } }