Reputation: 637
Sample Xml:
<TestXML>
<TestDecimal attr1="Required" attr2="false">0.34</TestDecimal>
<TestInteger attr1="MyAttr" attr2="1" DateAdded="">25</TestInteger>
</TestXML>
Class Definitions:
public class TestXML {
public DecimalValue TestDecimal;
public IntegerValue TestInteger;
}
public class IntegerValue {
[XmlText]
public int value {get; set;}
[XmlAnyAttribute]
public XmlAttribute[] XAttributes {get; set;}
}
public class DecimalValue {
[XmlText]
public decimal value {get; set;}
[XmlAnyAttribute]
public XmlAttribute[] XAttributes {get; set;}
}
Code to deserialize:
XmlSerializer serializer = new XmlSerializer(typeof(TestXML));
using (FileStream fs = new FileStream(@"C:\Test.xml", FileMode.Open)) {
TestXML myxml = (TestXML)serializer.Deserialize(fs);
}
In testing this it comes back with the integer value but not the decimal value:
myxml
TestDecimal
value | 0
XAttributes {string[2]}
[0] Name="attr1", Value="Required"
[1] Name="attr2", Value="false"
TestInteger
value | 25
XAttributes {string[3]}
[0] Name="attr1", Value="MyAttr"
[1] Name="attr2", Value="1"
[2] Name="DateAdded", Value=""
Is there something about deserializing decimals that would cause it come back as 0? With the primitive type of decimal the decimal value comes back fine.
Upvotes: 1
Views: 2063
Reputation: 28839
You must be doing something differently in your actual code than what you are showing here. Your code does not compile as posted - specifically class definitions don't have () after their names in C#.
This works for me as expected (the decimal value gets deserialized correctly):
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace Test
{
public class TestXML
{
public DecimalValue TestDecimal;
public IntegerValue TestInteger;
}
public class IntegerValue
{
[XmlText]
public int value {get; set;}
[XmlAnyAttribute]
public XmlAttribute[] XAttributes {get; set;}
}
public class DecimalValue
{
[XmlText]
public decimal value {get; set;}
[XmlAnyAttribute]
public XmlAttribute[] XAttributes {get; set;}
}
class Program
{
static void Test()
{
XmlSerializer serializer = new XmlSerializer(typeof(TestXML));
using (FileStream fs = new FileStream("Test.xml", FileMode.Open))
{
TestXML myxml = (TestXML)serializer.Deserialize(fs);
}
}
static void Main(string[] args)
{
Test();
}
}
}
This is with a local test.xml file copied to the bin directory containing this data:
<TestXML>
<TestDecimal attr1="Required" attr2="false">0.34</TestDecimal>
<TestInteger attr1="MyAttr" attr2="1" DateAdded="">25</TestInteger>
</TestXML>
Upvotes: 2