问题的序列化/反序列化包含CDATA属性
问题描述:
我需要反序列化/序列化下面的XML文件的XML:问题的序列化/反序列化包含CDATA属性
<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#类:
[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; }
}
,一切工作几乎是完美的,但反序列化后在地方
<![CDATA[<strong>Image 1</strong>]]>
我有
<strong>Image 1</strong>
我试图使用XmlCDataSection作为Content属性的类型,但这种类型不允许使用XmlText属性。不幸的是我不能改变XML结构。
我该如何解决这个问题?
答
这应该有助于
private string content;
[XmlText]
public string Content
{
get { return content; }
set { content = XElement.Parse(value).Value; }
}
答
首先声明一个属性为XmlCDataSection
public XmlCDataSection ProjectXml { get; set; }
在这种情况下projectXml是一个字符串的XML
ProjectXml = new XmlDocument().CreateCDataSection(projectXml);
时序列化你的消息,你将有你的好格式(通知)
<?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>
答
大多数在StackOverflow上提出的解决方案仅适用于序列化,而不是反序列化。这个将会完成这项工作,如果你需要从代码中获取/设置值,请使用我添加的额外属性PriceUrlByString。
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);
}
}
'图像1]]>'和'<强>图像1 < /强>'是相同的东西。你的问题在哪里? – Tomalak 2011-03-19 19:27:57
读取xml的另一个应用程序有一些问题'<强>图片1 < /强>' – higi 2011-03-19 20:03:55
这意味着这个其他应用程序不能理解XML,应该修复。 – Tomalak 2011-03-19 20:45:40