与序列化/反序列化包含CDATA属性的XML问题
问题描述:
我要反序列化/序列化下面的XML文件:
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>
我的C#类:
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>]]>
我
<strong>Image 1</strong>
我试图用XmlCDataSection类型的内容属性,但这种类型没有与XMLTEXT属性所允许的。不幸的是,我不能改变的XML结构。
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?
答
首先声明一个属性XmlCDataSection
First declare a property as XmlCDataSection
public XmlCDataSection ProjectXml { get; set; }
在这种情况下projectXml是一个XML字符串
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>