簡體   English   中英

如何解析XML字符串c#

[英]How to Parse XML String c#

我正在嘗試將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"

這指定了任何元素的默認命名空間。 此外, currencyrateCube元素中的屬性 - 它們不是子元素。

所以你想要這樣的東西:

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

請注意,因為我將currency屬性轉換為string ,所以對於未指定該屬性的任何貨幣,您最終將使用null Name屬性。 如果要跳過這些元素,可以在Select之前或之后使用Where子句。

另請注意,我已將Value的類型更改為decimal而不是float - 您不應將float用於與貨幣相關的值。 (有關詳細信息,請參閱此問題 。)

此外,您應該考慮使用XDocument.Load來加載XML:

XDocument doc = XDocument.Load(address);

然后就不需要自己創建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