2013-11-01 60 views
1
 private void nsButton3_Click(object sender, EventArgs e) 
    { 
     string geoip = nsTextBox4.Text; 
     WebClient wc = new WebClient(); 
     string geoipxml = (wc.DownloadString("http://freegeoip.net/xml/" + geoip)); 
     StringBuilder output = new StringBuilder(); 
     using (XmlReader reader = XmlReader.Create(new StringReader(geoipxml))) 
     { 
      reader.ReadToFollowing("Response"); 
      reader.MoveToFirstAttribute(); 
      string geoipanswer = reader.Value; 
      MessageBox.Show(geoipanswer); 
     } 
    } 
} 
} 

问题是当我单击按钮时显示一个空的文本框。假设IP地址显示。 XML响应看起来像这样..解析XML c#问题

<Response> 
<Ip>69.242.21.115</Ip> 
<CountryCode>US</CountryCode> 
<CountryName>United States</CountryName> 
<RegionCode>DE</RegionCode> 
<RegionName>Delaware</RegionName> 
<City>Wilmington</City> 
<ZipCode>19805</ZipCode> 
<Latitude>39.7472</Latitude> 
<Longitude>-75.5918</Longitude> 
<MetroCode>504</MetroCode> 
<AreaCode>302</AreaCode> 
</Response> 

任何想法?

回答

5

是的。 Ip是一个要素,你想读它,如果它是和属性:

reader.MoveToFirstAttribute(); 

我会建议切换到LINQ到XML:

string geoipxml = (wc.DownloadString("http://freegeoip.net/xml/" + geoip)); 
var xDoc = XDocument.Parse(geoipxml); 
string geoipanswer = (string)xDoc.Root.Element("Ip"); 
MessageBox.Show(geoipanswer); 

你需要using System.Xml.Linq到让它起作用。