3

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

私が間違っているところ。

4

2 に答える 2

5

問題は、XML のルート要素にこれが含まれているのに対し、名前空間のない要素を探していることです。

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

これにより、任意の要素のデフォルトの名前空間が指定されます。また、要素内の属性currencyあり、サブ要素ではありません。rateCube

したがって、次のようなものが必要です。

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これらの要素をスキップしたい場合はWhereSelect.

また、通貨関連の値には使用しValueないdecimalfloatください。float(詳細については、この質問を参照してください。)

XDocument.Loadさらに、 XML の読み込みに使用することを検討する必要があります。

XDocument doc = XDocument.Load(address);

その後、自分で作成する必要はありませんWebRequest

于 2013-09-07T08:22:37.523 に答える
2
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();
于 2013-09-07T08:26:11.213 に答える