XML序列化 - XmlCDataSection为Serialization.XmlText [英] XML Serialization - XmlCDataSection as Serialization.XmlText
问题描述
我在使用C#序列化CDATA部分问题
I am having problems serializing a cdata section using c#
我需要序列化XmlCDataSection对象属性为元素的InnerText。
I need to serialize XmlCDataSection object property as the innertext of the element.
我要寻找的结果是这样的:
The result I am looking for is this:
<Test value2="Another Test">
<![CDATA[<p>hello world</p>]]>
</Test>
要生产这种,我使用这个对象:
To produce this, I am using this object:
public class Test
{
[System.Xml.Serialization.XmlText()]
public XmlCDataSection value { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute()]
public string value2 { get; set; }
}
在使用上的值属性下面的错误被抛出的XMLTEXT注释。
When using the xmltext annotation on the value property the following error is thrown.
System.InvalidOperationException:
有反射性
'价值'的错误。 --->
System.InvalidOperationException:
无法序列
型System.Xml.XmlCDataSection成员价值。
XmlAttribute / XMLTEXT不能用于
编码复杂类型
System.InvalidOperationException: There was an error reflecting property 'value'. ---> System.InvalidOperationException: Cannot serialize member 'value' of type System.Xml.XmlCDataSection. XmlAttribute/XmlText cannot be used to encode complex types
如果我注释掉的注释,序列化将工作,但CDATA节被放置到这是没有良好的什么,我试图做一个价值元素:
If I comment out the annotation, the serialization will work but the cdata section is placed into a value element which is no good for what I am trying to do:
<Test value2="Another Test">
<value><![CDATA[<p>hello world</p>]]></value>
</Test>
任何人都可以点我在正确的方向,以得到这个工作。
Can anybody point me in the right direction to getting this to work.
谢谢,亚当
推荐答案
感谢理查德,只是现在有机会得到回本。我想我已经用你的建议,解决了这个问题。
Thanks Richard, only now had chance to get back to this. I think I have resolved the problem by using your suggestion. I have created a CDataField object using the following:
public class CDataField : IXmlSerializable
{
private string elementName;
private string elementValue;
public CDataField(string elementName, string elementValue)
{
this.elementName = elementName;
this.elementValue = elementValue;
}
public XmlSchema GetSchema()
{
return null;
}
public void WriteXml(XmlWriter w)
{
w.WriteStartElement(this.elementName);
w.WriteCData(this.elementValue);
w.WriteEndElement();
}
public void ReadXml(XmlReader r)
{
throw new NotImplementedException("This method has not been implemented");
}
}
这篇关于XML序列化 - XmlCDataSection为Serialization.XmlText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!