XML列表序列化[英] XML list serialization

本文是小编为大家收集整理的关于XML列表序列化的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有以下 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; }
}

本文地址:https://www.itbaoku.cn/post/1557014.html

问题描述

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