Lock
Lock

Reputation: 5522

How do I deserialize XML into an object if that objects element root tag is not present?

I am working with an API that returns all content inside of a <body> XML tag.

I am deserializing my XML into 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 do I deserialize my XML into an object if there is no root tag for that object?

For example, I receive 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 in fact a Offer object, however because that tag doesn't exist, I am unsure how to deserialize it into that object. It works if I add those properties to the Body model.

Upvotes: 3

Views: 195

Answers (1)

GreatAndPowerfulOz
GreatAndPowerfulOz

Reputation: 1775

    /// <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;
    }

Upvotes: 1

Related Questions