如何将属性添加到标有XmlArrayAttribute集合? [英] How to add an attribute to a collection marked with XmlArrayAttribute?

查看:119
本文介绍了如何将属性添加到标有XmlArrayAttribute集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢这里的格式的XML: http://pastie.org/1311506 (不插入在这里,因为评论解析器删除标记)。

I have an XML of the format like here: http://pastie.org/1311506 (not inserting it here because comment parser deletes tags).

此XML是serealized /使用以下code反序列化的:

This XML is serealized/deserialized using the following code:

[XmlRoot("products")]
public class Products
{
    [XmlElement("label")]
    public string Label { get; set; }

    [XmlArray("cars")]
    [XmlArrayItem("car")]
    public Car[] Cars { get; set; }
}

public class Car
{
    [XmlAttribute("name")]
    public string Name { get; set; }
}

...

var products = new Products
                   {
                       Label = "1",
                       Cars = new[]
                                  {
                                      new Car {Name = "BMW"},
                                      new Car {Name = "Volvo"}
                                  }
                   };
var serializer = new XmlSerializer(typeof(Products));
var writer = new StringWriter();
serializer.Serialize(writer, products);
Console.WriteLine(writer);

我需要一个额外的属性<车> 节点名为键入(喜欢这里:的 http://pastie.org/1311514 )。我该怎么办呢?

I need an additional attribute to <cars> node called type (like here: http://pastie.org/1311514). How can I do it?

在换言之,如何以解析所述第二pastie链路中所示的格式的XML定义数据类(产品及汽车或者其他人如有必要)?

In other words, how to define data classes (Products and Car and maybe others if necessary) in order to parse XML of the format shown in the second pastie link?

推荐答案

有没有简单的方法来做到这一点,因为集合了的XmlSerializer 忽略所有成员,它只是序列化集合的项目。不过,如果你只是想反序列化而忽略了键入属性,它不是一个问题:未知的属性只会被忽略

There's no easy way to do that, because for collections the XmlSerializer ignores all members, it only serializes the items of the collection. However, if you only want to deserialize it and ignore the type attribute, it's not an issue : unknown attributes will just be ignored.

如果您需要获得的值类型,你可以声明一个类,不是集合,而是包含集合。类似的东西:

If you need to get the value of type, you can declare a class that is not a collection, but contains the collection. Something like that:

public class Cars
{
    [XmlElement("car")]
    public Car[] Items { get; set; }

    [XmlAttribute("type")]
    public string Type { get; set; }
}

在你的产品类,只是声明汽车键入汽车<财产/ code>只是一个的XmlElement 属性:

In your Products class, just declare the Cars property of type Cars with just a XmlElement attribute:

[XmlRoot("products")]
public class Products
{
    [XmlElement("label")]
    public string Label { get; set; }

    [XmlElement("cars")]
    public Cars Cars { get; set; }
}

这篇关于如何将属性添加到标有XmlArrayAttribute集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆