【问题标题】:C# Deserialize text in XML mixed content as custom object?C#将XML混合内容中的文本反序列化为自定义对象?
【发布时间】:2011-09-11 00:17:48
【问题描述】:

是否可以有一个 XML,其中一个元素具有混合内容,并将混合元素中的文本反序列化为自定义对象而不是 string

我试过了:

    [XmlText(typeof(textType))]
    [XmlElement("query", typeof(templateBodyQuery))]
    [XmlElement("expand", typeof(expandType))]
    [XmlElement("insert", typeof(expandTypeInsert))]
    public object[] Items { get; set; }

预计文本项将被序列化为 textType,但我收到 'textType' cannot be used as 'xml text' 错误。

这是我的textType 班级:

public class textType
{
    [XmlText]
    public string Value { get; set; }
}

【问题讨论】:

    标签: c# xml-serialization


    【解决方案1】:

    您不能对 XmlText 使用非原始类型。此外,我不确定我是否理解该 xml 的结构,因为您不能在单个节点下拥有 XmlText 和 XmlElements。

    我认为这就是你想要做的:

    [XmlElement("textType",typeof(textType))]
    [XmlElement("query", typeof(templateBodyQuery))]
    [XmlElement("expand", typeof(expandType))]
    [XmlElement("insert", typeof(expandTypeInsert))]
    public object[] Items { get; set; }
    

    反序列化:

    <Test>
        <textType>example</textType>
        <query>...</query>
        <expand>...</expand>
    </Test>
    

    到一个类Test,它在Items数组的开头有一个textType对象,Value是“example”

    【讨论】:

      猜你喜欢
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多