XML - 将属性反序列化为 Xml 子树 [英] XML - Deserialize property as Xml sub-tree
问题描述
当我反序列化一个 xml 字符串时,我需要在一个名为 prop2
的字符串属性上保存一个 XElement outerXml.
When I'm deserializing a xml string, I need to save a XElement outerXml on a string property called prop2
.
我的 XML:
<MyObj>
<prop1>something</prop1>
<prop2>
<RSAKeyValue>
<Modulus>...</Modulus>
<Exponent>...</Exponent>
</RSAKeyValue>
</prop2>
<prop3></prop3>
</MyObj>
我的对象:
public class MyObj
{
[XmlElement("prop1")]
public string prop1 { get; set; }
[XmlText]
public string prop2 { get; set; }
[XmlElement(ElementName = "prop3", IsNullable = true)]
public string prop3 { get; set; }
}
我正在使用 XmlSerializer
反序列化,如下所示:
I'm deserializing using XmlSerializer
, like this:
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(myXmlString));
我尝试使用 [XmlText]
在 prop2
中保存 XML 文本,但我只得到 null
.
I tried to use [XmlText]
to save XML text in prop2
But I'm only getting null
.
我需要做什么来保存
喜欢 prop2
中的文字吗?
What I need to do to save <RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent></RSAKeyValue>
like text in prop2
?
推荐答案
XmlText
will give value as XML encoding as text (">prop2<..."
) 参见 XmlTextAttribute
XmlText
will give value as XML encoded as text (">prop2<..."
) see XmlTextAttribute
默认情况下,XmlSerializer 将类成员序列化为 XML 元素.但是,如果将 XmlTextAttribute 应用于成员,则 XmlSerializer 会将其值转换为 XML 文本.这意味着该值被编码到 XML 元素的内容中.
By default, the XmlSerializer serializes a class member as an XML element. However, if you apply the XmlTextAttribute to a member, the XmlSerializer translates its value into XML text. This means that the value is encoded into the content of an XML element.
一种可能的解决方案 - 使用 XmlNode
作为属性类型:
One possible solution - use XmlNode
as type of the property:
public class MyObj
{
[XmlElement("prop1")]
public string prop1 { get; set; }
public XmlNode prop2 { get; set; }
[XmlElement(ElementName = "prop3", IsNullable = true)]
public string prop3 { get; set; }
}
var r = (MyObj)serializer.Deserialize(new StringReader(myXmlString));
Console.WriteLine(r.prop2.OuterXml);
或者,您可以使整个对象实现自定义 Xml 序列化或具有与 XML 匹配的自定义类型(以正常读取)并具有将对象表示为 XML 字符串的附加属性.
Alternatively you may make whole object implement custom Xml serialization or have custom type that matches XML (to read normally) and have additional property to represent that object as XML string.
这篇关于XML - 将属性反序列化为 Xml 子树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!