如何使用XmlArrayItem反序列化xml

时间:2009-12-09 16:04:55

标签: asp.net xml xml-serialization

我想像这样反序列化xml:

<Product>
    <Classification>
        <NewClassification>1</NewClassification>
        <NewClassification>2</NewClassification>
        <NewClassification>3</NewClassification>
        <OldClassification>A</OldClassification>
        <OldClassification>B</OldClassification>
    </Classification>
</Product>

我的课程是:

public class Product
{
    public Classification Classification { get; set; }
}

public class Classification
{
    [XmlArrayItem(typeof(int), ElementName = "NewClassification")]
    public List<int> NewClassificationList { get; set; }
    [XmlArrayItem(typeof(int), ElementName = "OldClassification")]
    public List<int> OldClassificationList { get; set; }
}

为什么这段代码错了?

1 个答案:

答案 0 :(得分:3)

除了上面提到的“熊会吃掉你”的“int literal”问题之外,你不能以你想要的方式将你的课程序列化(至少我想不到一个这样做的方式) 不依赖于自定义序列化(例如,实现IXmlSerializable或其他方法)。

您的基本问题是您在分类中有两个单独的集合,您希望将它们显示为单个集合。

IXmlSerialization路线非常简单。只需在您的Classification类上按如下方式实现它,您就会得到所需的结果。

public class Classification : IXmlSerializable
{
    public List<int> NewClassificationList { get; set; }
    public List<string> OldClassificationList { get; set; }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        foreach (var item in NewClassificationList)
        {
            writer.WriteElementString("NewClassification", item.ToString());
        }
        foreach (var item in OldClassificationList)
        {
            writer.WriteElementString("OldClassification", item.ToString());
        }
    }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        throw new NotImplementedException();
    }
}

添加了ReadXml实现

ReadXml可以按如下方式实现:

public void ReadXml(System.Xml.XmlReader reader)
{
    var product = new Product();

    product.Classification = new Classification { NewClassificationList = new List<int>(),  ldClassificationList = new List<string>()};

    reader.ReadStartElement("Classification");

    while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
    {
        switch (reader.Name)
        {
            case "NewClassification":
                product.Classification.NewClassificationList.Add(reader.ReadElementContentAsInt());
                break;
            case "OldClassification":
                product.Classification.OldClassificationList.Add(reader.ReadElementContentAsString());
                break;
            default:
                throw new NotSupportedException("Unsupported node: " + reader.Name);
           } 
        }
        reader.ReadEndElement();
    }