当我反序列化一个 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
.
我需要做什么来拯救 <RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent></RSAKeyValue>
喜欢 prop2
中的文字?
最佳答案
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 字符串的附加属性。
关于c# - XML - 将属性反序列化为 Xml 子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33741048/