加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何解析XML字符串c#

发布时间:2020-12-16 22:41:54 所属栏目:百科 来源:网络整理
导读:我正在尝试将 XML字符串解析为列表,结果计数始终为零. string result = ""; string address = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"; // Create the web request HttpWebRequest request = WebRequest.Create(address) as HttpWe
我正在尝试将 XML字符串解析为列表,结果计数始终为零.

string result = "";
            string address = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";

            // Create the web request  
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

            // Get response  
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream  
                StreamReader reader = new StreamReader(response.GetResponseStream());

                // Read the whole contents and return as a string  
                result = reader.ReadToEnd();
            }

            XDocument doc = XDocument.Parse(result);

            var ListCurr = doc.Descendants("Cube").Select(curr => new CurrencyType() 
                    { Name = curr.Element("currency").Value,Value = float.Parse(curr.Element("rate").Value) }).ToList();

哪里出错了

解决方法

问题是你正在寻找没有命名空间的元素,而XML在根元素中包含这个元素:

xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"

这指定了任何元素的默认命名空间.此外,货币和汇率是多维数据集元素中的属性 – 它们不是子元素.

所以你想要这样的东西:

XNamespace ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";
var currencies = doc.Descendants(ns + "Cube")
                    .Select(c => new CurrencyType {
                                     Name = (string) c.Attribute("currency"),Value = (decimal) c.Attribute("rate")
                                 })
                    .ToList();

请注意,因为我将货币属性转换为字符串,所以对于未指定该属性的任何货币,您最终将使用null Name属性.如果要跳过这些元素,可以在Select之前或之后使用Where子句.

另请注意,我已将Value的类型更改为decimal而不是float – 您不应将float用于与货币相关的值. (有关详细信息,请参阅this question.)

此外,您应该考虑使用XDocument.Load加载XML:

XDocument doc = XDocument.Load(address);

然后就不需要自己创建WebRequest等了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读