c# - XML 序列化 - XmlCDataSection 作为 Serialization.XmlText

标签 c# xml xml-serialization cdata

我在使用 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/

相关文章:

c# - ASP.NET Webform 在运行时错误上显示 Error.ASPX 页面

c# - 要求 Entity Framework 中共享公共(public)属性值的项目具有唯一值

c++ - boost ptree add_child 创建不需要的嵌套元素

xml - 如何在Marklogic Server中加载和查询word/excel文档?

C# XMLElement.OuterXML 在一行而不是格式

java - XML 编码 - 使用 UTF-8 格式的 Xstream 将文件中的 XML 文本转换为对象

c# - 在 C# 中如何获取网格中单元格的内容?

c# - 在运行时统一加载 MP3 文件

c# - 在构建过程中生成一个 Xml 序列化程序集

c# - .NET 4.x 有重大更改 : Release mode does NOT execute static initializers properly if first call is to default ctor during deserialization