Problem with Serialization/Deserialization an XML containing CDATA attribute

10,514

Solution 1

this should help

    private string content;

    [XmlText]
    public string Content
    {
        get { return content; }
        set { content = XElement.Parse(value).Value; }
    }

Solution 2

First declare a property as XmlCDataSection

public XmlCDataSection ProjectXml { get; set; }

in this case projectXml is a string xml

ProjectXml = new XmlDocument().CreateCDataSection(projectXml);

when you serialize your message you will have your nice format (notice )

<?xml version="1.0" encoding="utf-16"?>
<MessageBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="Message_ProjectStatusChanged">
  <ID>131</ID>
  <HandlerName>Plugin</HandlerName>
  <NumRetries>0</NumRetries>
  <TriggerXml><![CDATA[<?xml version="1.0" encoding="utf-8"?><TmData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="9.0.0" Date="2012-01-31T15:46:02.6003105" Format="1" AppVersion="10.2.0" Culture="en-US" UserID="0" UserRole=""><PROJECT></PROJECT></TmData>]]></TriggerXml>
  <MessageCreatedDate>2012-01-31T20:28:52.4843092Z</MessageCreatedDate>
  <MessageStatus>0</MessageStatus>
  <ProjectId>0</ProjectId>
  <UserGUID>8CDF581E44F54E8BAD60A4FAA8418070</UserGUID>
  <ProjectGUID>5E82456F42DC46DEBA07F114F647E969</ProjectGUID>
  <PriorStatus>0</PriorStatus>
  <NewStatus>3</NewStatus>
  <ActionDate>0001-01-01T00:00:00</ActionDate>
</MessageBase>
Share:
10,514
higi
Author by

higi

Updated on June 05, 2022

Comments

  • higi
    higi almost 2 years

    I need to deserialize/serialize the xml file below:

    <items att1="val">
    <item att1="image1.jpg">
             <![CDATA[<strong>Image 1</strong>]]>
    </item>
    <item att1="image2.jpg">
             <![CDATA[<strong>Image 2</strong>]]>
    </item>     
    </items>
    

    my C# classes:

    [Serializable]
    [XmlRoot("items")]    
    public class RootClass
    {
      [XmlAttribute("att1")]
      public string Att1 {set; get;}
    
      [XmlElement("item")]  
      public Item[] ArrayOfItem {get; set;}
    }
    
      [Serializable]
    public class Item
    {
        [XmlAttribute("att1")]
        public string Att1 { get; set; }
    
        [XmlText]
        public string Content { get; set; }
    }
    

    and everything works almost perfect but after deserialization in place

    <![CDATA[<strong>Image 1</strong>]]>
    

    I have

    &lt;strong&gt;Image 1&lt;/strong&gt;
    

    I was trying to use XmlCDataSection as type for Content property but this type is not allowed with XmlText attribute. Unfortunately I can't change XML structure.

    How can I solve this issue?