How to deserialize XML into an object if that object root element tag is missing?
I am working with an API that returns all content inside an <body>
XML tag .
I am deserializing my XML to objects using the following function:
public TObject ParseXML<TObject>(string xml)
{
using (TextReader reader = new StreamReader(GetMemoryStream(xml)))
{
XmlSerializer serialiser = new XmlSerializer(typeof(TObject));
return (TObject)serialiser.Deserialize(reader);
}
}
How can I deserialize my XML into an object if there is no root tag for that object?
For example, I get the following response:
<body>
<active>true</active>
<allow_quote_requests>false</allow_quote_requests>
<currency_iso_code>AUD</currency_iso_code>
Everything after the body tag is actually an object Offer
, however, since this tag doesn't exist, I'm not sure how to deserialize it into this object. It works if I add these properties to the model Body
.
+3
source to share
1 answer
/// <summary>
/// Deserialize an object from the given reader which has been positioned at the start of the appropriate element.
/// </summary>
/// <typeparam name="T">the type of the object to deserialize</typeparam>
/// <param name="reader">the reader from which to deserialize the object</param>
/// <returns>an object instance of type 'T'</returns>
public static T DeserializeFromXml<T>(XmlReader reader)
{
T value = (T)new XmlSerializer(typeof(T), new XmlRootAttribute(reader.Name) { Namespace = reader.NamespaceURI }).Deserialize(reader);
return value;
}
+1
source to share