2

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">
<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>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Decimal.Parse would throw exception if it could not parse the data, right?
That is correct. If you look into TryParse, however, it contains built in exception handling.
Also looking over the XML that you added, I think that simply trying out .Value will give you the results you are looking for. Explicit parsing shouldn't be needed, although it would still be possible.
what I am doing now is importing it all as string, and then converting to decimal with TryParse, but I still think that (decimal?) should had worked.
the problem (I think) is that d.Element("ForexSelling") = <ForexSelling>0.05077</ForexSelling> while d.Element("ForexSelling").Value = 0.05077

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.