2013-11-01 82 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到讓它起作用。