XML - 将 属性 反序列化为 Xml 子树
XML - Deserialize property as Xml sub-tree
当我反序列化 xml 字符串时,我需要在名为 prop2
.
的字符串 属性 上保存 XElement outerXml
我的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
反序列化,如下所示:
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(myXmlString));
我尝试使用 [XmlText]
在 prop2
中保存 XML 文本,但我只得到 null
。
我需要做什么才能像 prop2
中的文本一样保存 <RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent></RSAKeyValue>
?
XmlText
将给出 XML 编码为文本 (">prop2<..."
) 的值,参见 XmlTextAttribute
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
作为 属性 的类型:
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 字符串.
当我反序列化 xml 字符串时,我需要在名为 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
反序列化,如下所示:
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(myXmlString));
我尝试使用 [XmlText]
在 prop2
中保存 XML 文本,但我只得到 null
。
我需要做什么才能像 prop2
中的文本一样保存 <RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent></RSAKeyValue>
?
XmlText
将给出 XML 编码为文本 (">prop2<..."
) 的值,参见 XmlTextAttribute
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
作为 属性 的类型:
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 字符串.