I have a problem with CDATA deserialization using the standard .Net XmlSerializer.
Update . I get XML from an external system and I cannot influence its format, so I cannot include CData in a separate attribute element.
Serialization gives the following:
<?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>
Deserialization does not restore the object to its original state.
Here is the class that is being serialized:
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; } } }
Here is a test that fails:
[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);
I found the same problem here, but no answer: XmlSerializer, XmlAnyElement and CDATA
Konstantin spirin
source share