Reputation: 548
I'm parsing an XML document from a web-service which returns an array of objects.
An object has fields that contain floating-point values, it looks like so:
<Valute ID="R01010">
<NumCode>036</NumCode>
<CharCode>AUD</CharCode>
<Nominal>1</Nominal>
<Name>Australian Dollar</Name>
<Value>14,4200</Value>
</Valute>
I am successfully reading the document into an XDocument
object like so:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet)))
{
XDocument xmlDoc = new XDocument();
try
{
xmlDoc = XDocument.Parse(sr.ReadToEnd());
DesiredDate = DateTime.ParseExact(xmlDoc.Element("ValCurs").Attribute("Date").Value, "dd.MM.yyyy", new CultureInfo("ru-RU"));
result = new List<CBRItem>();
foreach (var valuteElement in xmlDoc.Element("ValCurs").Elements("Valute"))
{
CBRItem item = CBRItem.FromXElement(valuteElement);
if (item != null)
{
result.Add(item);
}
else
{
Console.WriteLine("Could not convert from Valute XML element:\n" + valuteElement.ToString());
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
And I process each object in the array like so:
public static CBRItem FromXElement(XElement elem)
{
CBRItem result = new CBRItem();
try
{
result.ID = elem.Attribute("ID").Value;
result.NumCode = elem.Element("NumCode").Value;
result.CharCode = elem.Element("CharCode").Value;
result.Nominal = short.Parse(elem.Element("Nominal").Value, new CultureInfo("ru-RU"));
result.Name = elem.Element("Name").Value;
result.Value = decimal.Parse(elem.Element("Value").Value, new CultureInfo("ru-RU"));
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return result;
}
I've debugged my code an verified that the XElement
objects that I pass into the FromXElement
functions are filled with appropriate data (like mentioned in the beginning).
But I'm getting a System.FormatException
on the decimal
parsing line
result.Value = decimal.Parse(elem.Element("Value").Value, new CultureInfo("ru-RU"));
On some PCs but not mine or the one I have at work.
This is really weird and I've even specifid the culture in order to eliminate the parsing error which could occur because the NumberDecimalSeparator
being not a comma in the current culture. (The culture is ru-RU
because the web-service is Russian and I think that's the appropriate choice in that case)
So, what could be causing this issue?
Upvotes: 2
Views: 213
Reputation: 244
Possibly the NumberDecimalSeparator
is set to something different than ,
on your system for the culture ru-RU
.
You can explicitly set the NumberDecimalSeparator
on the CultureInfo
:
var cultureInfo = new CultureInfo("ru-RU");
cultureInfo.NumberFormat.NumberDecimalSeparator = ",";
...
result.Value = decimal.Parse(elem.Element("Value").Value, cultureInfo);
Upvotes: 3