简体   繁体   English

如何解析XML字符串c#

[英]How to Parse XML String c#

I'm trying to parse XML string into list, result count is always zero. 我正在尝试将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();

where I'm going wrong. 哪里出错了

The problem is that you're looking for elements without a namespace, whereas the XML contains this in the root element: 问题是你正在寻找没有命名空间的元素,而XML在根元素中包含这个元素:

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

That specifies the default namespace for any element. 这指定了任何元素的默认命名空间。 Also, currency and rate are attributes within the Cube elements - they're not subelements. 此外, currencyrateCube元素中的属性 - 它们不是子元素。

So you want something like: 所以你想要这样的东西:

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

Note that because I'm casting the currency attribute to string , you'll end up with a null Name property for any currencies which don't specify that attribute. 请注意,因为我将currency属性转换为string ,所以对于未指定该属性的任何货币,您最终将使用null Name属性。 If you want to skip those elements, you can do so with a Where clause either before or after the Select . 如果要跳过这些元素,可以在Select之前或之后使用Where子句。

Also note that I've changed the type of Value to decimal rather than float - you shouldn't use float for currency-related values. 另请注意,我已将Value的类型更改为decimal而不是float - 您不应将float用于与货币相关的值。 (See this question for more details.) (有关详细信息,请参阅此问题 。)

Additionally, you should consider using XDocument.Load to load the XML: 此外,您应该考虑使用XDocument.Load来加载XML:

XDocument doc = XDocument.Load(address);

Then there's no need to create the WebRequest etc yourself. 然后就不需要自己创建WebRequest等了。

XDocument doc = XDocument.Parse(result);
XNamespace ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";

var ListCurr = doc.Descendants(ns + "Cube")
                    .Where(c=>c.Attribute("currency")!=null) //<-- Some "Cube"s do not have currency attr.
                    .Select(curr => new CurrencyType  
                    { 
                        Name = curr.Attribute("currency").Value, 
                        Value = float.Parse(curr.Attribute("rate").Value) 
                    })
                    .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM