我正在使用API返回<body>
XML标记内的所有内容。
我使用以下函数将XML反序列化为对象:
public TObject ParseXML<TObject>(string xml)
{
using (TextReader reader = new StreamReader(GetMemoryStream(xml)))
{
XmlSerializer serialiser = new XmlSerializer(typeof(TObject));
return (TObject)serialiser.Deserialize(reader);
}
}
如果该对象没有根标记,如何将我的XML反序列化为对象?
例如,我收到以下回复:
<body>
<active>true</active>
<allow_quote_requests>false</allow_quote_requests>
<currency_iso_code>AUD</currency_iso_code>
body标签之后的所有内容实际上都是Offer
对象,但由于该标记不存在,我不确定如何将其反序列化为该对象。如果我将这些属性添加到Body
模型,它就可以工作。
答案 0 :(得分:1)
/// <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;
}