Reputation: 1249
When I'm deserializing a xml string, I need to save a XElement outerXml on a string property called prop2
.
My XML:
<MyObj>
<prop1>something</prop1>
<prop2>
<RSAKeyValue>
<Modulus>...</Modulus>
<Exponent>...</Exponent>
</RSAKeyValue>
</prop2>
<prop3></prop3>
</MyObj>
My object:
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; }
}
I'm deserializing using XmlSerializer
, like this:
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(myXmlString));
I tried to use [XmlText]
to save XML text in prop2
But I'm only getting null
.
What I need to do to save <RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent></RSAKeyValue>
like text in prop2
?
Upvotes: 1
Views: 1118
Reputation: 100547
XmlText
will give value as XML encoded as text (">prop2<..."
) see 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.
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);
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.
Upvotes: 4