C# 将 XML 混合内容中的文本反序列化为自定义对象?

标签 c# xml-serialization

是否可以拥有一个 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; }
}

最佳答案

您不能对 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>

TestItems 数组的开头有一个 textType 对象,Value 为“example”

关于C# 将 XML 混合内容中的文本反序列化为自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7375519/

相关文章:

c# - iTextSharp - 填充动态表字段

C# 使用 : constructor in a different method

c# - 我可以使用 C# 将 XML 直接序列化为字符串而不是流吗?

asp.net - 找不到文件“C :\WINDOWS\TEMP\xxxx. dll

asp.net-mvc - 如何在 View 中保留复杂对象,同时仅更新一小部分

c# - 将 XML 反序列化为对象 : XML element with xsi:nil ="true" should have null value (and not empty value) for respective property in object

c# - 将时间值的字符串表示形式解析为 TimeSpan

c# - Xamarin Forms 上的 MigraDocCore 中的 "Image could not be read."

c# - 如何使用 Azure 语音转文本和 C# 生成时间戳?

java - 没有 XML 声明的 XStream(new StaxDriver())