我使用标准的.Net XmlSerializer来解决CDATA反序列化问题。
更新:我从外部系统获取XML并且我不能影响它的格式,因此我无法将CData包含在单独的属性元素中。
序列化给出了这个:
<?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"><![CDATA[Hello, world!]]></MyClass>
反序列化不会将对象恢复为原始状态。
这是序列化的类:
public class MyClass
{
string _data;
[XmlIgnore]
public string Data
{
get { return _data; }
set { _data = value; }
}
[XmlAnyElement]
public XmlCDataSection CData
{
get { return new XmlDataDocument().CreateCDataSection(Data); }
set { Data = value.Value; }
}
}
这是失败的测试:
[Test]
public void CData_as_inner_text_test()
{
MyClass item = new MyClass();
item.Data = "Hello, world!";
XmlSerializer serializer = new XmlSerializer(item.GetType());
string serialized;
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, item);
serialized = sw.GetStringBuilder().ToString();
}
MyClass deserialized;
using (StringReader sr = new StringReader(serialized))
{
deserialized = (MyClass)serializer.Deserialize(sr);
}
Assert.AreEqual(item.Data, deserialized.Data); // For some reason, deserialized.Data == null
}
我在这里发现了同样的问题,但没有答案: XmlSerializer, XmlAnyElement and CDATA
答案 0 :(得分:9)
CData属性最终为null,因为CDATA部分的内容最终会在Data属性中被忽略...
<MyClass><![CDATA[Hello, world!]]></MyClass>
绝对等同于:
<MyClass>Hello, world!</MyClass>
您不应该关心外部应用程序是否将MyClass的内容写为CData。同样,外部应用程序不应该关心你如何写出来。
IOW,这应该就是你所需要的:
public class MyClass
{
string _data;
[XmlText]
public string Data
{
get { return _data; }
set { _data = value; }
}
}
答案 1 :(得分:0)
首先将属性声明为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>