从.NET将类型序列化为XML

时间:2012-08-13 17:20:12

标签: c# .net xmlserializer ixmlserializable

我有这个C#4.0类型

public class DecimalField
{
    public decimal Value { get; set; }
    public bool Estimate { get; set; }
}

我想使用XmlSerializer将类型序列化为

<Val Estimate="true">123</Val>

理想情况下,如果其值为false,我想省略Estimate属性。将估计值更改为可以为空的bool是可以接受的。

从此类型到此XML表示需要哪些属性/实现?

感谢。

3 个答案:

答案 0 :(得分:2)

不确定您是否可以仅使用属性有条件地输出估算值。但是你definitelly可以实现IXmlSerializable并检查WriteXml方法中的Estimate值。

这是example

答案 1 :(得分:1)

有条件地省略Estimate需要大量编码。我不会这样。

XmlWriter writer = XmlWriter.Create(stream, new XmlWriterSettings() { OmitXmlDeclaration = true });

var ns = new XmlSerializerNamespaces();
ns.Add("", "");

XmlSerializer xml = new XmlSerializer(typeof(DecimalField));

xml.Serialize(writer, obj, ns);

-

[XmlRoot("Val")]
public class DecimalField
{
    [XmlText]
    public decimal Value { get; set; }
    [XmlAttribute]
    public bool Estimate { get; set; }
}

您也可以使用Linq2Xml手动序列化您的课程

List<XObject> list = new List<XObject>();
list.Add(new XText(obj.Value.ToString()));
if (obj.Estimate) list.Add(new XAttribute("Estimate", obj.Estimate));

XElement xElem = new XElement("Val", list.ToArray());

xElem.Save(stream);

答案 2 :(得分:0)

这是尽可能接近(不包括Estimate属性)而不实现IXmlSerializable:

[XmlRoot("Val")]
public class DecimalField
{
    [XmlText()]
    public decimal Value { get; set; }
    [XmlAttribute("Estimate")]
    public bool Estimate { get; set; }
}

使用IXmlSerializable,您的类看起来像这样:

[XmlRoot("Val")]
public class DecimalField : IXmlSerializable
{
    public decimal Value { get; set; }
    public bool Estimate { get; set; }

    public void WriteXml(XmlWriter writer)
    {
        if (Estimate == true)
        {
            writer.WriteAttributeString("Estimate", Estimate.ToString());
        }

        writer.WriteString(Value.ToString());
    }

    public void ReadXml(XmlReader reader)
    {
        if (reader.MoveToAttribute("Estimate") && reader.ReadAttributeValue())
        {
            Estimate = bool.Parse(reader.Value);
        }
        else
        {
            Estimate = false;
        }

        reader.MoveToElement();
        Value = reader.ReadElementContentAsDecimal();
    }

    public XmlSchema GetSchema()
    {
        return null;
    }
}

您可以像这样测试您的课程:

    XmlSerializer xs = new XmlSerializer(typeof(DecimalField));

    string serializedXml = null;
    using (StringWriter sw = new StringWriter())
    {
        DecimalField df = new DecimalField() { Value = 12.0M, Estimate = false };
        xs.Serialize(sw, df);
        serializedXml = sw.ToString();
    }

    Console.WriteLine(serializedXml);

    using (StringReader sr = new StringReader(serializedXml))
    {
        DecimalField df = (DecimalField)xs.Deserialize(sr);

        Console.WriteLine(df.Estimate);
        Console.WriteLine(df.Value);
    }