我在使用 c# 序列化 cdata 部分时遇到问题
我需要将 XmlCDataSection 对象属性序列化为元素的内部文本。
我要找的结果是这样的:
<Test value2="Another Test">
<![CDATA[<p>hello world</p>]]>
</Test>
为了产生这个,我正在使用这个对象:
public class Test
{
[System.Xml.Serialization.XmlText()]
public XmlCDataSection value { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute()]
public string value2 { get; set; }
}
在 value 属性上使用 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 部分被放置到一个值元素中,这对我正在尝试做的事情没有好处:
<Test value2="Another Test">
<value><![CDATA[<p>hello world</p>]]></value>
</Test>
任何人都可以为我指明正确的方向,让它发挥作用。
谢谢,亚当
最佳答案
谢谢理查德,现在才有机会回到这个话题。我想我已经通过使用你的建议解决了这个问题。我使用以下方法创建了一个 CDataField 对象:
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");
}
}
关于c# - XML 序列化 - XmlCDataSection 作为 Serialization.XmlText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1398680/