.NET Framework - Serialiazing pure HTML via DataContractSerializer (CDATA?)

Asked By Joerg Battermann
12-Apr-08 08:34 AM
Hello there,

I have a class which I can serialize and deserialize just fine, but
one of its fields actually contains html data, including <, > etc. Now
in the serialized .xml files, these are actually escaped or converted
into entities (<) etc.

How do I dump the html just the way it is without escaping and just
its raw html content?


Thanks,
-Joerg :)
XmlNodeType.CDATA
(1)
System.Xml.Schema.XmlSchema
(1)
XmlNodeType.EndElement
(1)
TypeDescriptor.GetProperties
(1)
InvalidOperationException
(1)
CreateCDataSection
(1)
IsNullOrEmpty
(1)
System.ComponentModel
(1)
  Marc Gravell replied...
10-Apr-08 10:10 AM
Is it html or xhtml?

I don't know about DataContractSerializer, but with XmlSerializer you
can use [XmlText] to serialize a member as xml rather than an escaped
string; I don't know if DataContractSerializer respects this in
[DataContract] mode (my guess would be: not, but worth a try) - but it
probably will in [Serializable] mode (if you see what I mean).

Marc
  Marc Gravell replied...
10-Apr-08 10:19 AM
It did not work. Oh well.
  Joerg Battermann replied...
12-Apr-08 08:34 AM
;)

but thanks.

I'd like to keep the DataContract Serializer for various reasons...
just need to get (x)html out :\

-J
  Marc Gravell replied...
10-Apr-08 10:42 AM
OK; how about:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

[DataContract]
public sealed class Foo
{
public string Bar { get; set; }
[DataMember(Name="Bar")]
private XmlElement BarXml
{
get
{
if(string.IsNullOrEmpty(Bar)) return null;
XmlDocument doc = new XmlDocument();
doc.LoadXml(Bar);
return doc.DocumentElement;
}
set
{
Bar = value == null ? null : value.OuterXml;
}
}
}
static class Program
{
static void Main()
{
Foo foo = new Foo { Bar = @"<xml id=""abc"">blop</xml>" };

DataContractSerializer dcs = new
DataContractSerializer(typeof(Foo));
StringWriter writer2 = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(writer2))
{
dcs.WriteObject(xw, foo);
xw.Close();
}
string xml2 = writer2.ToString();
}
}
  Marc Gravell replied...
10-Apr-08 10:45 AM
And before you ask the next question (xmlns):

[DataContract(Namespace="")]
  Marc Gravell replied...
10-Apr-08 10:52 AM
And if you really must have CDATA:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

[DataContract]
public sealed class Foo
{
public string Bar { get; set; }
[DataMember(Name="Bar")]
private XmlElement BarXml
{
get
{
if(string.IsNullOrEmpty(Bar)) return null;
XmlDocument doc = new XmlDocument();
doc.AppendChild(doc.CreateElement("Content"))
.AppendChild(doc.CreateCDataSection(Bar));
return doc.DocumentElement;
}
set
{
Bar = value == null ? null : value.FirstChild.InnerText;
}
}
}
static class Program
{
static void Main()
{
Foo foo = new Foo { Bar = @"<xml id=""abc"">blop</xml>" };

DataContractSerializer dcs = new
DataContractSerializer(typeof(Foo));
StringWriter writer = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(writer))
{
dcs.WriteObject(xw, foo);
xw.Close();
}
string xml = writer.ToString();

StringReader reader = new StringReader(xml);
using (XmlReader xr = XmlReader.Create(reader))
{
foo = (Foo) dcs.ReadObject(xr);
}

}
}
  Marc Gravell replied...
12-Apr-08 08:34 AM
And yet another version (gets rid of the extra element, and less CPU):

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;
using System.ComponentModel;

public sealed class CDataWrapper : IXmlSerializable
{
// implicit to/from string
public static implicit operator string(CDataWrapper value)
{
return value == null ? null : value.Value;
}
public static implicit operator CDataWrapper(string value)
{
return value == null ? null : new CDataWrapper { Value =
value };
}
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
// "" => <Node/>
// "Foo" => <Node><![CDATA[Foo]]></Node>
public void WriteXml(XmlWriter writer)
{
if (!string.IsNullOrEmpty(Value))
{
writer.WriteCData(Value);
}
}
// <Node/> => ""
// <Node></Node> => ""
// <Node>Foo</Node> => "Foo"
// <Node><![CDATA[Foo]]></Node> => "Foo"
public void ReadXml(XmlReader reader)
{
if (reader.IsEmptyElement)
{
Value = "";
}
else
{
reader.Read();
switch (reader.NodeType)
{
case XmlNodeType.EndElement:
Value = ""; // empty after all...
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
Value = reader.ReadContentAsString();
break;
default:
throw new InvalidOperationException("Expected text/
cdata");
}
}
}
// underlying value
public string Value { get; set; }
public override string ToString()
{
return Value;
}
}

// example usage
[DataContract(Namespace="http://myobjects/")]
public sealed class MyType
{
public string SomeValue { get; set; }
[DataMember(Name = "SomeValue", EmitDefaultValue = false)]
private CDataWrapper SomeValueCData
{
get { return SomeValue; }
set { SomeValue = value; }
}

public string EmptyTest { get; set; }
[DataMember(Name = "EmptyTest", EmitDefaultValue = false)]
private CDataWrapper EmptyTestCData
{
get { return EmptyTest; }
set { EmptyTest = value; }
}

public string NullTest { get; set; }
[DataMember(Name = "NullTest", EmitDefaultValue = false)]
private CDataWrapper NullTestCData
{
get { return NullTest ; }
set { NullTest = value; }
}
}

// test rig
static class Program
{
static void Main()
{

DataContractSerializer dcs =
new DataContractSerializer(typeof(MyType));

StringWriter writer = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(writer))
{
MyType foo = new MyType
{
SomeValue = @"&<t\d",
NullTest = null,
EmptyTest = ""
};
ShowObject("Original", foo);

dcs.WriteObject(xw, foo);
xw.Close();
}
string xml = writer.ToString();
ShowObject("Xml", xml);

StringReader reader = new StringReader(xml);
using (XmlReader xr = XmlReader.Create(reader))
{
MyType bar = (MyType) dcs.ReadObject(xr);
ShowObject("Recreated", bar);
}
}
static void ShowObject(string caption, object obj)
{
Console.WriteLine();
Console.WriteLine("** {0} **", caption );
Console.WriteLine();
if (obj == null)
{
Console.WriteLine("(null)");
} else if (obj is string) {
Console.WriteLine((string)obj);
}
else
{
foreach (PropertyDescriptor prop in
TypeDescriptor.GetProperties(obj))
{
Console.WriteLine("{0}:\t{1}", prop.Name,
prop.GetValue(obj) ?? "(null)");
}
}
}
}
  Joerg Battermann replied...
12-Apr-08 08:35 AM
Ohhh awesome. Makes sense.. will give this a try over the weekend here
with my class models...


Thanks!!
  Joerg Battermann replied...
18-Apr-08 01:33 AM
It worked!

thank you :)
help
Urgent problem with System.Xml.Schema.XmlSchema .NET Framework A set of xsd files has been working fine for us at this SchemaCollectionCompiler.Compile() at System.Xml.Schema.SchemaCollectionCompiler.Execute(XmlSchema schema, SchemaInfo schemaInfo, Boolean compileContentModel) at System.Xml.Schema.XmlSchema.CompileSchema(XmlSchemaCollection xsc, XmlResolver resolver, SchemaInfo schemaInfo, String ns, ValidationEventHandler validationEventHandler, XmlNameTable nameTable, Boolean CompileContentModel
NET and XMLSchemaSet .NET Framework Hello, Using .NET 2.0 and the System.XML.Schema.XMLSchema class. I am adding some schemas into the XMLSchemaSet object using XmlSchemaSet.Add. The schemas Helena Kotas, MSFT keywords: .NET, and, XMLSchemaSet description: Hello, Using .NET 2.0 and the System.XML.Schema.XMLSchema class. I am adding some schemas into the XMLSchemaSet object using XmlSchemaSet.Add. The schem
Xml.Schema.XmlSchemaSet xs) { System.Xml.Serialization.XmlSerializer schemaSerializer = new System.Xml.Serialization.XmlSerializer(typeof(System.Xml.Schema.XmlSchema)); System.Xml.Schema.XmlSchema s = AnyTextData2.Schema; xs.XmlResolver = new System.Xml.XmlUrlResolver(); xs.Add(s); return new System
it is below: namespace MyNamespace { [XmlRoot("dictionary")] public class SerializableDictionary : Dictionary<string, string> , IXmlSerializable { public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { bool wasEmpty = reader.IsEmptyElement; / / read like to create something similar here. Any suggestions / alternatives are appreciated. Thanks, Chris C# Discussions System.Xml.Schema.XmlSchema (1) XmlArrayItemAttribute (1) System.Xml.XmlReader (1) System.Xml.XmlWriter (1) WriteStartElement (1) WriteEndElement (1