XMLSerialization of complex content

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I would like to serialize some XML where one of the elements contains html
content:

<MyXML><DataContent><p><b>ABC News Online</b></p></DataContent><MyXML>

However the XMLSerializer gives me the following exception:

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

I would like the serializer to read out all the HTML content from the
<DataContent> element.

My class looks like:

using System.Xml.Serialization;
namespace ABC.MyXML_5.BL
{
[XmlRoot("MyXML")]
public class MyXML_5
{
private string element_datacontent;

[XmlElement]
public string DataContent
{
get { return element_datacontent; }
set { element_datacontent = value; }
}
}
}

My code looks like:

//10.Create some XML
StringBuilder l_strBldrXML = new StringBuilder();

l_strBldrXML.Append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
l_strBldrXML.Append("<MyXML>");
l_strBldrXML.Append("<DataContent>");
l_strBldrXML.Append("<p><b>ABC News Online</b></p>");
l_strBldrXML.Append("</DataContent>");
l_strBldrXML.Append("</MyXML>");

//20.Put XML into an in memory stream
Stream l_StreamTest =
new
MemoryStream(Encoding.GetEncoding("Windows-1252").GetBytes(l_strBldrXML.ToString()));

//30.Deserialize into instance of a class
XmlSerializer l_Serializer = new
XmlSerializer(typeof(ABC.MyXML_5.BL.MyXML_5));

ABC.MyXML_5.BL.MyXML_5 l_MyXMLDocument;

l_MyXMLDocument =
(ABC.MyXML_5.BL.MyXML_5)l_Serializer.Deserialize(l_StreamTest);

l_StreamTest.Close();

Assert.IsTrue(l_MyXMLDocument.DataContent == "<p>ABC News Online</p>");
 
Hi,

You have a couple of simple options:

1. CDATA
<![CDATA[<p><b>ABC News Online</b></p>]]>
2. Xml Encoding
&lt;p&gt;&lt;b&gt;ABC News Online&lt;/b&gt;&lt;/p&gt;

In either case your assert statement will pass, but only if you make a small adjustment first so it looks like this: "<p><b>ABC News
Online</b></p>" .

If you don't have control over the xml content then you should use an XmlDocument object or XmlReader first to go through every node
and fix the bad xml. Your sample is, after all, bad xml if the p and b tags are not part of your valid schema definition.
 
Back
Top