Problem with Serialization/Deserialization an XML containing CDATA attribute
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]
开发者_StackOverflow中文版[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
<strong>Image 1</strong>
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?
this should help
private string content;
[XmlText]
public string Content
{
get { return content; }
set { content = XElement.Parse(value).Value; }
}
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>
Most of the solutions presented in StackOverflow works only for Serialization, and not Deserialization. This one will do the job, and if you need to get/set the value from your code, use the extra property PriceUrlByString that I added.
private XmlNode _priceUrl;
[XmlElement("price_url")]
public XmlNode PriceUrl
{
get
{
return _priceUrl;
}
set
{
_priceUrl = value;
}
}
[XmlIgnore]
public string PriceUrlByString
{
get
{
// Retrieves the content of the encapsulated CDATA
return _priceUrl.Value;
}
set
{
// Encapsulate in a CDATA XmlNode
XmlDocument xmlDocument = new XmlDocument();
this._priceUrl = xmlDocument.CreateCDataSection(value);
}
}
精彩评论