Serialize a type in XML from .NET.

I have this type of C # 4.0

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

I want to use XmlSerializer to type serialize in

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

Ideally, I want to omit the Estimate attribute if its value is false. It is possible to change the grade to nullable bool.

What attributes / implementations are needed to transition from this type to this XML representation?

Thanks.

+4
source share
3 answers

Not sure if you can derive a conditional estimate with attributes only. But you can definitely implement IXmlSerializable and check the Estimate value inside the WriteXml method.

Here is an example

+2
source

Conditionally omit Estimate requires encoding. I would not 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); 
+1
source

This is about as close as you can get (the Estimate attribute is always on) 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 as follows:

  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
source

All Articles