XmlSerializer的 - 反序列化不同的元素集合相同的元素元素、不同、序列化、XmlSerializer

2023-09-02 02:03:39 作者:久伴依赖病i

我有以下的XML一部分的模式,我不能改变。 NUMBER,区域,何况,联邦有列:

I have the following XML part which schema I can't change. NUMBER, REGION, MENTION, FEDERAL are columns:

<COLUMNS LIST="20" PAGE="1" INDEX="reg_id">
  <NUMBER WIDTH="3"/>
  <REGION WIDTH="60"/>
  <MENTION WIDTH="7"/>
  <FEDERAL WIDTH="30"/>
</COLUMNS>

我想将它反序列化到公开名单&LT;柱&GT;列{获取;集;} 属性。因此,元素名称会去Column.Name。列类:

I want to deserialize it to public List<Column> Columns {get;set;} property. So element name would go to Column.Name. Column class:

public class Column
{
   //Name goes from Element Name
   public string Name {get;set;}
   [XmlAttribute("WIDTH")]
   public int Width {get;set;}
}

是否有可能与XmlSerializer类?

Is it possible with XmlSerializer class?

推荐答案

如果您不能更改架构,则架构更可能不会改变。 (如果这不是一个有效的假设,请让我知道。)在这种情况下,使用的XmlSerializer的可能是矫枉过正。为什么不使用LINQ到XML?

If you are not allowed to change the schema, then the schema is more likely not to change. (If this is not a valid assumption, please let me know.) In that case, the use of XmlSerializer may well be overkill. Why not use Linq to XML?

class Program
{
    static void Main(string[] args)
    {
        XDocument doc = XDocument.Load(@".ResourcesSample.xml");

        var columns = from column in doc.Descendants("COLUMNS").Descendants()
                      select new Column(column.Name.LocalName, int.Parse(column.Attribute("WIDTH").Value));

        foreach (var column in columns)
            Console.WriteLine(column.Name + " | " + column.Width);
    }

    class Column
    {
        public string Name { get; set; }
        public int Width { get; set; }

        public Column(string name, int width)
        {
            this.Name = name;
            this.Width = width;
        }
    }
}

在的这段上面装载的示例XML,然后创建一个从它的列的枚举。简单有效。然而,这需要.NET 3.0或更高版本,因此,如果这不是一个选择,那么这是不是你的解决方案,很遗憾。

The snippit above loads your sample XML and then creates an enumeration of columns from it. Simple and effective. However, this requires .NET 3.0 or later, so if that is not an option for you then this is not the solution for you, unfortunately.

微软的LINQ的链接到XML文档:

A link to Microsoft's Linq to XML documentation:

http://msdn.microsoft.com/en-us/library/ bb387098.aspx