我有一个XML字符串,它可以从API调用中检索为xml字符串。我需要在应用程序中将其转换为视图模型,以便可以在视图中显示它。 但是,由于viewmodel仅具有很少的节点/元素,因为xml文档中有该节点/元素,所以当我尝试对其进行反序列化时会抛出异常。下面是代码和错误。
API端点返回此
<response>
<data>
<categories>
<category>
<id>1</id>
<name>hats</name>
</category>
</categories>
</data>
</response>
代码:
namespace CatApp.Models
{
[XmlRoot("Categories")]
public class CategoriesViewModel
{
public CategoriesViewModel()
{
_categories = new List<Category>();
}
private List<Category> _categories;
[XmlElement("Category")]
public List<Category> Categories
{
get { return _categories; }
set { value = _categories; }
}
public class Category
{
[XmlElement("Id")]
public int Id { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
}
}
}
public static async Task<CategoriesViewModel> GetAllCategories()
{
var model = new CategoriesViewModel();
try
{
var response = await client.GetStreamAsync(uri);
model = DeserializeXMLToObject<CategoriesViewModel>(response);
}
catch (Exception ex)
{
var exception = ex;
}
return model;
}
public static T DeserializeXMLToObject<T>(Stream stream)
{
T returnObject = default(T);
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
returnObject = (T)serializer.Deserialize(stream);
}
catch (Exception ex)
{
}
return returnObject;
}
错误于 System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader,字符串encodingStyle,XmlDeserializationEvents事件)
在System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
在CatApp.Controllers.HomeController.DeserializeXMLToObject [T](Stream 流中) C:\ Users \ umerh \ source \ repos \ CatAPI \ CatApp \ Controllers \ HomeController.cs:line 50
答案 0 :(得分:1)
首先,C#属性中的元素名称必须与XML中的元素名称匹配。区分大小写:Categories
不等于categories
,依此类推。
[XmlRoot("categories")] // <--
public class CategoriesViewModel
{
public CategoriesViewModel()
{
_categories = new List<Category>();
}
private List<Category> _categories;
[XmlElement("category")] // <--
public List<Category> Categories
{
get { return _categories; }
set { value = _categories; }
}
public class Category
{
[XmlElement("id")] // <--
public int Id { get; set; }
[XmlElement("name")] // <--
public string Name { get; set; }
}
}
第二,您可以跳过一些xml元素,如下所示:
public static T DeserializeXMLToObject<T>(Stream stream)
{
T returnObject = default(T);
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (var xmlReader = XmlReader.Create(stream))
{
xmlReader.ReadToFollowing("categories"); // Skip elements before categories node
returnObject = (T)serializer.Deserialize(xmlReader);
}
}
catch (Exception ex)
{
}
return returnObject;
}