WhatsRighteous
WhatsRighteous

Reputation: 13

Parsing XML c# issue

        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);
        }
    }
}
}

The issue is when I click the button an empty textbox displays. The IP Address is suppose to display. A XML response looks like this..

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

Any ideas?

Upvotes: 1

Views: 109

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

Yes. Ip is an element, and you're trying to read it as if it was and attribute:

reader.MoveToFirstAttribute();

I would advice to switch to 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);

You'll need using System.Xml.Linq to make it work.

Upvotes: 5

Related Questions