如何解析XML字符串c#
我试图将XML字符串解析到列表中,结果计数始终为零如何解析XML字符串c#,c#,xml,webrequest,C#,Xml,Webrequest,我试图将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 Ht
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"
指定任何元素的默认命名空间。另外,currency
和rate
是Cube
元素中的属性-它们不是子元素
所以你想要的是:
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
,因此对于未指定该属性的任何货币,您将得到一个nullName
属性。如果要跳过这些元素,可以在Select
之前或之后使用Where
子句
还请注意,我已将值的类型更改为十进制
,而不是浮动
——您不应该对货币相关的值使用浮动
。(有关详细信息,请参阅。)
另外,您应该考虑使用加载XML:
XDocument doc = XDocument.Load(address);
这样就不需要自己创建WebRequest
etc XDocument doc=XDocument.Parse(结果);
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();
XNS=”http://www.ecb.int/vocabulary/2002-08-01/eurofxref";
var ListCurr=文档子体(ns+“多维数据集”)
.Where(c=>c.Attribute(“currency”)!=null)//新的CurrencyType
{
名称=货币属性(“货币”).值,
Value=float.Parse(curr.Attribute(“rate”).Value)
})
.ToList();
@BassamAlugili:这真的不是它的复制品。@Manish我已经删除了它并投票给你!当乔恩回答一个问题时,那一定是个好问题!谢谢感谢您让我知道XDocument doc=XDocument.Load(地址)@Manish:我现在将其编辑为使用decimal
而不是float
——请查看我对您接受的答案的评论,因为如果当前线程区域性使用,
作为十进制分隔符,这将无法正常工作。最好实际解释问题所在,而不仅仅是发布代码。我还建议使用cast而不是float.Parse
-在使用逗号作为小数分隔符的区域性中,此代码将失败。@JonSkeet您是对的,但您已经对其进行了很好的解释。