是否可以拥有一个 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>
类 Test
在 Items
数组的开头有一个 textType 对象,Value
为“example”
关于C# 将 XML 混合内容中的文本反序列化为自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7375519/