Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you serialize a string as CDATA using XmlSerializer?

Is it possible via an attribute of some sort to serialize a string as CDATA using the .Net XmlSerializer?

like image 324
jamesaharvey Avatar asked Sep 04 '09 15:09

jamesaharvey


People also ask

How do I add Cdata to XML?

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 &.

Can we use Cdata in XML attribute?

No, The markup denoting a CDATA Section is not permitted as the value of an attribute.

How does the XmlSerializer work C#?

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.

Is XmlSerializer thread safe?

4 Answers. Show activity on this post. This type is thread safe.


2 Answers

[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> 
like image 79
pr0gg3r Avatar answered Oct 07 '22 12:10

pr0gg3r


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;     } } 
like image 25
Philip Rieck Avatar answered Oct 07 '22 12:10

Philip Rieck