views:

95

answers:

1

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>

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

Is it possible with XmlSerializer class?

+2  A: 

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(@".\Resources\Sample.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;
        }
    }
}

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.

A link to Microsoft's Linq to XML documentation:

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

Allen E. Scharfenberg
Good idea. May use XPath if Linq-to-XML is undesirable for some reason.
Anton Tykhyy
Very good point! XPath is quite similar to Linq to XML, and XPath does not require .NET 3.0 and later.
Allen E. Scharfenberg