c# - XML 列表序列化

标签 c# xml linq xml-serialization xmlserializer

我有以下 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 做到这一点。

最佳答案

您可以使用 XmlArrayXmlArrayItem 属性:

public class Product
{
    [XmlArray]
    [XmlArrayItem("Id")]
    public List<int> Categories { get; set; }
}

关于c# - XML 列表序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30263736/

相关文章:

javascript - 预检具有无效的 HTTP 状态代码 404 Jquery AJAX POST

c# - Azure 计划程序 Rest API - 更新作业错误 : Schedules are not supported for recurrence unit 'Hour'

c# - 使用编码从 XML 字符串中获取字节数组

.net - NHibernate.Linq : session becomes dirty after select

c# - 如何选择对包含多行 LIST 的条目使用 LINQ?

c# - 匿名类型属性 setter

c# - dotnet run --https 的项目问题

c++ - boost property_tree 在循环中添加节点

python - XML 解析 - ElementTree vs SAX 和 DOM

c# - 比如使用动态 lambda 表达式搜索日期时间字段