【问题标题】:Parsing XML c# issue解析 XML c# 问题
【发布时间】:2013-11-01 21:14:28
【问题描述】:
        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>

有什么想法吗?

【问题讨论】:

    标签: c# xml parsing


    【解决方案1】:

    是的。 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 才能使其工作。

    【讨论】:

      猜你喜欢
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      相关资源
      最近更新 更多