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 响应看起来像这样..

<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>

有任何想法吗?

4

1 回答 1

5

是的。Ip是一个元素,并且您尝试将其作为属性来读取:

reader.MoveToFirstAttribute();

我建议切换到 LINQ to 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让它工作。

于 2013-11-01T21:16:26.623 回答