由于格式化,XML反序列化在十进制解析时崩溃

时间:2013-07-03 00:33:58

标签: c# .net xml serialization xml-deserialization

当我尝试将XML解析为对象时,抛出了System.FormatException。据我所知,这是由于System.Xml.Serialization.XmlSerializer.Deserialize中使用的文化,假设一个点作为十进制字符,但xml包含一个逗号。

该对象如下所示:


public sealed class Transaction
{
    [XmlElement("transactionDate")]
    public DateTime TransactionDate { get; set; }

    [XmlElement("transactionAmount")]
    public decimal Amount { get; set; }

    [XmlElement("transactionDescription")]
    public string Description { get; set; }

    [XmlElement("transactionType")]
    public int Type { get; set; }

    public static Transaction FromXmlString(string xmlString)
    {
        var reader = new StringReader(xmlString);
        var serializer = new XmlSerializer(typeof(Transaction));
        var instance = (Transaction) serializer.Deserialize(reader);

        return instance;
    }
}

xml:


<transaction>
    <transactionDate> 2013-07-02 <transactionDate>
    <transactionAmount>-459,00</transactionAmount>
    <transactionDescription>description</transactionDescription>
    <transactionType>1</transactionType>
</transaction>

我通过引入第二个使用我自己的文化解析第一个属性的方法来实现它:


namespace MyNamespace
{
    [XmlRoot("transaction"), XmlType("Transaction")]
    public sealed class Transaction
    {
        [XmlElement("transactionDate")]
        public DateTime TransactionDate { get; set; }

        [XmlElement("transactionAmount")]
        public string Amount { get; set; }

        public decimal AmountAsDecimal {
            get
            {
                decimal value;
                Decimal.TryParse(Amount, NumberStyles.Any, CultureInfo.CreateSpecificCulture("sv-SE"), out value);
                return value;
            }
        }

        [XmlElement("transactionDescription")]
        public string Description { get; set; }

        [XmlElement("transactionType")]
        public int Type { get; set; }

        public static Transaction FromXmlString(string xmlString)
        {
            var reader = new StringReader(xmlString);
            var serializer = new XmlSerializer(typeof(Transaction));
            var instance = (Transaction) serializer.Deserialize(reader);

            return instance;
        }
    }
}


暴露了我不想要的额外属性。

所以我的问题是:还有另一种方法可以做到这一点,而不是迭代每个元素并将其“手动”解析/分配给对象吗?

3 个答案:

答案 0 :(得分:5)

XML序列化程序使用标准化的Number和DateTime格式,该标准在W3C架构数据类型规范http://www.w3.org/TR/xmlschema-2/中定义。

不要指望XmlSerializer关注帖子的CultureInfo,它会故意使用标准格式来确保您可以独立于文化/区域设置进行序列化/反序列化。

答案 1 :(得分:5)

您可以做的是拥有一个属性,用于序列化/反序列化decimal

请参阅:Partially deserialize XML to Object

[XmlType("transaction")]
public sealed class Transaction
{
    [XmlElement("transactionDate")]
    public DateTime TransactionDate { get; set; }

    [XmlIgnore]
    public decimal Amount { get; set; }

    [XmlElement("transactionAmount")]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    public string AmountSerialized
    {
        get
        {
            return Amount.ToString(CultureInfo.CreateSpecificCulture("sv-SE"));
        }
        set
        {
            decimal amount;
            Decimal.TryParse(value, NumberStyles.Any, CultureInfo.CreateSpecificCulture("sv-SE"), out amount);
            Amount = amount;
        }
    }

    [XmlElement("transactionDescription")]
    public string Description { get; set; }

    [XmlElement("transactionType")]
    public int Type { get; set; }

    public static Transaction FromXmlString(string xmlString)
    {
        var reader = new StringReader(xmlString);
        var serializer = new XmlSerializer(typeof(Transaction));
        var instance = (Transaction) serializer.Deserialize(reader);

        return instance;
    }
}

这样您就可以获取/设置Amount,而无需担心它是如何序列化的。由于这是一个DTO,因此您可以创建另一个类,而不使用AmountSerialized作为您的域对象(并使用类似AutoMapper的内容使转换无痛)。

用法:

var data = @"<transaction>
                <transactionDate>2013-07-02</transactionDate>
                <transactionAmount>-459,00</transactionAmount>
                <transactionDescription>description</transactionDescription>
                <transactionType>1</transactionType>
            </transaction>";

var serializer = new XmlSerializer(typeof(Transaction));

using(var stream = new StringReader(data))
using(var reader = XmlReader.Create(stream))
{
     Console.Write(serializer.Deserialize(reader));
}

transactionDate的结尾标记中也有拼写错误。

答案 2 :(得分:2)

如果您了解生成XML的文化,一个简单的解决方案是在反序列化之前将当前线程的文化切换到该文化。

    System.Globalization.CultureInfo oCurrentCulture = null;
    try
    {
        // Save the current culture
        oCurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");

        // Do your work
    }
    finally
    {
                    // Restore the saved culture
        System.Threading.Thread.CurrentThread.CurrentCulture = oCurrentCulture;
    }