Serialize type into XML from .NET

273 Views Asked by At

I have this C# 4.0 type

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

I want to use XmlSerializer to serialize the type into

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

Ideally, I want to omit the Estimate attribute if its value is false. Changing Estimate to a nullable bool is acceptable.

What attributes/implementations are required to go from this type to this XML representation?

Thanks.

3

There are 3 best solutions below

0
On

This is about as close as you can get (an Estimate attribute is always included) without implementing IXmlSerializable:

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

With IXmlSerializable, your class looks like this:

[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;
    }
}

You can test your class like this:

    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);
    }
0
On

Not sure if you can output Estimate conditionally with attributes only. But you definitelly can implement IXmlSerializable and check Estimate value inside WriteXml method.

Here is an example

0
On

Conditionally omitting Estimate would require a lof of coding. I wouldn't go that way.

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; }
}

You can also manually serialize your class using 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);