示例Xml:
<TestXML>
<TestDecimal attr1="Required" attr2="false">0.34</TestDecimal>
<TestInteger attr1="MyAttr" attr2="1" DateAdded="">25</TestInteger>
</TestXML>
班级定义:
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;}
}
反序列化代码:
XmlSerializer serializer = new XmlSerializer(typeof(TestXML));
using (FileStream fs = new FileStream(@"C:\Test.xml", FileMode.Open)) {
TestXML myxml = (TestXML)serializer.Deserialize(fs);
}
在测试中,它返回整数值但不是十进制值:
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=""
是否有关于反序列化小数的内容会导致它返回0?使用十进制的原始类型,十进制值返回正常。
答案 0 :(得分:2)
您必须在实际代码中执行与此处显示的内容不同的操作。您的代码不会像已发布的那样编译 - 特别是类定义在C#中的名称之后没有()。
这对我来说符合预期(十进制值得到正确的反序列化):
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();
}
}
}
将本地test.xml文件复制到包含此数据的bin目录:
<TestXML>
<TestDecimal attr1="Required" attr2="false">0.34</TestDecimal>
<TestInteger attr1="MyAttr" attr2="1" DateAdded="">25</TestInteger>
</TestXML>