Is it possible via an attribute of some sort to serialize a string as CDATA using the .Net XmlSerializer?
CDATA sections can appear inside element content and allow < and & character literals to appear. A CDATA section begins with the character sequence <! [CDATA[ and ends with the character sequence ]]>. Between the two character sequences, an XML processor ignores all markup characters such as <, >, and &.
No, The markup denoting a CDATA Section is not permitted as the value of an attribute.
The XmlSerializer creates C# (. cs) files and compiles them into . dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. These serialization assemblies can be generated in advance and signed by using the SGen.exe tool.
4 Answers. Show activity on this post. This type is thread safe.
[Serializable] public class MyClass { public MyClass() { } [XmlIgnore] public string MyString { get; set; } [XmlElement("MyString")] public System.Xml.XmlCDataSection MyStringCDATA { get { return new System.Xml.XmlDocument().CreateCDataSection(MyString); } set { MyString = value.Value; } } }
Usage:
MyClass mc = new MyClass(); mc.MyString = "<test>Hello World</test>"; XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); StringWriter writer = new StringWriter(); serializer.Serialize(writer, mc); Console.WriteLine(writer.ToString());
Output:
<?xml version="1.0" encoding="utf-16"?> <MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <MyString><![CDATA[<test>Hello World</test>]]></MyString> </MyClass>
In addition to the way posted by John Saunders, you can use an XmlCDataSection as the type directly, although it boils down to nearly the same thing:
private string _message; [XmlElement("CDataElement")] public XmlCDataSection Message { get { XmlDocument doc = new XmlDocument(); return doc.CreateCDataSection( _message); } set { _message = value.Value; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With