parsing xml when element is missing its value
I am trying to parse some currency data in xml format. Below code does not work, but when I parse it all as string, it does work.
CurrencyName = (string)d.Element("CurrencyName"),
ForexBuying = ((decimal?)d.Element("ForexBuying")),
ForexSelling = ((decimal?)d.Element("ForexSelling")),
BanknoteBuying = ((decimal?)d.Element("BanknoteBuying")),
BanknoteSelling = ((decimal?)d.Element("BanknoteSelling")),
CrossRateEuro = ((decimal?)d.Element("CrossRateEuro")),
CrossRateUSD = ((decimal?)d.Element("CrossRateUSD"))
Only CurrencyName exists in all elements, sometimes we have elements like
<BanknoteBuying></BanknoteBuying>
, some nodes do not carry the BanknoteBuying element at all.
Odd thing is I am getting a date/time parsing data error. So in short, casting it all to string works, but casting to appropriate nullable data type does not, data is well formed, and the local region is set correct to parse the decimal data.
<Currency Kod="RUB" CurrencyCode="RUB">开发者_JS百科
<Unit>1</Unit>
<Isim>RUS RUBLESİ</Isim>
<CurrencyName>RUSSIAN ROUBLE</CurrencyName>
<ForexBuying>0.05011</ForexBuying>
<ForexSelling>0.05077</ForexSelling>
<BanknoteBuying></BanknoteBuying>
<BanknoteSelling></BanknoteSelling>
<CrossRateUSD>30.5655</CrossRateUSD>
<CrossRateOther></CrossRateOther>
If you are having troubles with parsing, it might be worth it to try an explicit parse. For example
Decimal.Parse(d.Element("CrossRateUSD"));
Or even with TryParse might yeild some more info about it for you.
One more thing to try out, that I just noticed as I was writing this up is that what I think you are looking for is the value form the element, not the element itself. Without knowing your XML format, I can'T say 100% for sure, but try d.Element("CrossRateUSD").Value instead.
UPDATE: Added link to MSDN for TryParse.
精彩评论