3

I'm trying to dynamically generate an HTML table by using XmlSerializer and a set of classes like this:

[XmlInclude(typeof(Th))]
public class Td
{
    [XmlElement("span")]
    public string Designation { get; set; }

    [XmlAttribute("colspan")]
    public int ColSpan { get; set; }

    [XmlAttribute("rowspan")]
    public int RowSpan { get; set; }

    public Td(string designation, int colspan)
    {
        Designation = designation;
        ColSpan = colspan;
        RowSpan = 1;
    }

    public Td()
    {            
    }

}

The problem here is that the Designation property can have a tag as value like <option...>, so when I serialize my model I get &lt;option...&gt; instead of <option...>

I can solve the problem by using the string.Replace method like this: Replace("&lt;", "<").Replace("&gt;", ">");

Is there a clean way to get the expected result without the use of string.Replace?

Michael Liu
  • 52,147
  • 13
  • 117
  • 150
anouar.bagari
  • 2,084
  • 19
  • 30

2 Answers2

2

You can create another property that exposes Designation as an XmlNode:

[XmlIgnore]
public string Designation { get; set; }

[XmlElement("span")]
public XmlNode DesignationAsXml
{
    get
    {
        XmlDocument doc = new XmlDocument();
        doc.InnerXml = "<root>" + this.Designation + "</root>";
        return doc.DocumentElement.FirstChild;
    }
    set
    {
        throw new NotSupportedException();
    }
}
Michael Liu
  • 52,147
  • 13
  • 117
  • 150
  • How would Deserialization work here? A serialized object will not deserialize with the same information here. – Joel Peltonen Jan 16 '13 at 12:42
  • 1
    @Nenotlep: The OP's scenario didn't require deserialization so I didn't bother implementing the property setter. To do so, simply assign `value.OuterXml` to `this.Designation` instead of throwing an exception. – Michael Liu Jan 16 '13 at 15:49
0

Replacing it manually is needless. I think the best way is using System.XML.XmlWriter.WriteString class. Look for class definition here

Johnny_D
  • 4,592
  • 3
  • 33
  • 63