C# 将 XML 混合内容中的文本反序列化为自定义对象? [英] C# Deserialize text in XML mixed content as custom object?
问题描述
是否可以有一个 XML,其中一个元素具有混合内容,并将混合元素中的文本反序列化为自定义对象而不是 string
?
Is it possible to have an XML, one of which elements has mixed content, and deserialize the text in the mixed element as a custom object instead of as 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'
错误.
Expecting the text items would be serialized as textType
, but I get an 'textType' cannot be used as 'xml text'
error.
这是我的 textType
类:
public class textType
{
[XmlText]
public string Value { get; set; }
}
推荐答案
您不能对 XmlText 使用非原始类型.此外,我不确定我是否理解该 xml 的结构,因为您不能在单个节点下拥有 XmlText 和 XmlElements.
You can't use non primitive types for XmlText. Also I'm not sure I understand how that xml would be structured as you can't have XmlText and XmlElements under a single node.
我认为这就是你想要做的:
I think this is what you're trying to do:
[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"
To a class Test
that has a textType object at the start of the Items
array with Value
of "example"
这篇关于C# 将 XML 混合内容中的文本反序列化为自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!