问题描述
我有以下 XML:
<Product> <Categories> <Id>1</Id> <Id>2</Id> <Id>3</Id> <Id>4</Id> <Id>5</Id> <Id>6</Id> <Id>7</Id> <Id>8</Id> </Categories> </Product>
我正在使用 XmlSerializer 将其反序列化为 .NET 类型.我的目标是将其解散为:
public class Product { public List<int> Categories { get; set; } }
不幸的是,我没有设法将其取消实现为这种类型(Categories 属性为空).任何想法我该怎么做?
我设法做到了,但我对这样的解决方案不满意.
[Serializable] public class Categories { [XmlElement] public List<Int32> Id { get; set; } } public class Product { public Categories Categories { get; set; } }
我知道,我可以用 Linq to XML 做到这一点,但我想知道我是否可以用 XmlSerializer 做到这一点.
推荐答案
你可以使用 XmlArray 和 XmlArrayItem 属性:
public class Product { [XmlArray] [XmlArrayItem("Id")] public List<int> Categories { get; set; } }
问题描述
I have the following XML:
<Product> <Categories> <Id>1</Id> <Id>2</Id> <Id>3</Id> <Id>4</Id> <Id>5</Id> <Id>6</Id> <Id>7</Id> <Id>8</Id> </Categories> </Product>
I'm deserializing it to the .NET type using XmlSerializer. My goal is to have it deserealized as:
public class Product { public List<int> Categories { get; set; } }
Unfortunately I didn't manage to deserealize it to such type (the Categories property is empty). Any ideas how can I do it?
I managed to do it with, but I'm not happy with such solution.
[Serializable] public class Categories { [XmlElement] public List<Int32> Id { get; set; } } public class Product { public Categories Categories { get; set; } }
I know, I can do it with Linq to XML, but I wonder if I can do it with XmlSerializer.
推荐答案
You can use the XmlArray and XmlArrayItem attributes:
public class Product { [XmlArray] [XmlArrayItem("Id")] public List<int> Categories { get; set; } }