XmlSerializer: Get Text from Complex Type Property

Recently, I was working on some stuff dealing with Serializing/Deserializing XML with pre-defined XML tags as below:

<NOTE>
  <ID>3214245240a2e8e3eab0e54bcaab92</ID>
  <QUICKNOTE>This is a test note.</QUICKNOTE>
</NOTE>

I created the corresponding class as:

[Serializable]
[XmlRoot("NOTE")]
public class NoteXml
{
	[XmlElement("ID")]
	public string Id { get; set; }

	[XmlElement("QUICKNOTE")]
	public string QuickNote { get; set; }
}

I used XmlSerializer class to map the XML data to NoteXml class. I used below method for this:

public static T DeSerialize<T>(string xmlData) where T : class
{
	using (var stringReader = new StringReader(xmlData))
	{
		var deserializer = new XmlSerializer(typeof(T));
		var result = (T)deserializer.Deserialize(stringReader);
		return result;
	}
}

Due to some bad programming is done by another development team, I got <br /> in the QUICKNOTE tag and my program started throwing an exception:

Unexpected node type Element. ReadElementString method can only be called on elements with simple or empty content.

Actually, XmlSerializer class treat <br /> as another XML tag and leading to make QuickNote property a complex type but I know that it is just a string type and that <br /> is actually an HTML break.
I started searching to force a property to the content type in spite of complex type using XmlSerializer class but got nothing.
I spent some more time in thinking what can be the workaround for this and got an idea to declare complex type property of type "object" and added a new property also for getting the desired text. This lead to update my existing NoteXml class to:

[Serializable]
[XmlRoot("NOTE")]
public class NoteXml
{
	[XmlElement("ID")]
	public string Id { get; set; }

	[XmlElement("QUICKNOTE")]
	public object QuickNote { get; set; }
	
	[XmlIgnore]
    public string QuickNoteText => Utility.GetXmlOuterTextFromObject(QuickNote);
}

You may have noticed that I used a separate method "GetXmlOuterTextFromObject" for getting the content inside the XML tag. Here is its definition:

public static string GetXmlOuterTextFromObject(object xmlNode)
{
	//xmlNode is of type object (not XmlNode[]) when XML tag is closed in same opening tag like <test />
	var node = xmlNode as XmlNode[];
	return node != null ? string.Join("", node.Select(x => x.OuterXml)) : null;
}

Now, I started using QuickNoteText property when I want to get the content inside QuickNoteText irrespective of its complex type.


This workaround is just for getting the inner XML as it is. We can further update the GetXmlOuterTextFromObject() to get more customised text.