Gunnar
Gunnar

Reputation: 986

Deserialize XML

I want to deserialize a XML file in C# (.net 2.0).

The structure of the XML is like this:

<elements>
   <element>
     <id>
       123
     </id>
     <Files>
       <File id="887" description="Hello World!" type="PDF">
         FilenameHelloWorld.pdf
       </File>
     </Files>
   </element>
<elements>

When I try to deserialize this structure in C#, I get a problem with the Filename, the value is always NULL, even how I try to code my File class.

Please help me. ;-)

Upvotes: 0

Views: 2027

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

The following works fine for me:

public class element
{
    [XmlElement("id")]
    public int Id { get; set; }

    public File[] Files { get; set; }
}

public class File
{
    [XmlAttribute("id")]
    public int Id { get; set; }

    [XmlAttribute("description")]
    public string Description { get; set; }

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

    [XmlText]
    public string FileName { get; set; }
}

class Program
{
    static void Main()
    {
        using (var reader = XmlReader.Create("test.xml"))
        {
            var serializer = new XmlSerializer(typeof(element[]), new XmlRootAttribute("elements"));
            var elements = (element[])serializer.Deserialize(reader);

            foreach (var element in elements)
            {
                Console.WriteLine("element.id = {0}", element.Id);
                foreach (var file in element.Files)
                {
                    Console.WriteLine(
                        "id = {0}, description = {1}, type = {2}, filename = {3}", 
                        file.Id,
                        file.Description,
                        file.Type,
                        file.FileName
                    );
                }
            }

        }
    }
}

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062494

This should work...

[XmlRoot("elements")]
public class Elements {
    [XmlElement("element")]
    public List<Element> Items {get;set;}
} 
public class Element { 
    [XmlElement("id")]
    public int Id {get;set;}
    [XmlArray("Files")]
    [XmlArrayItem("File")]
    public List<File> Files {get;set;}
}
public class File {
    [XmlAttribute("id")]
    public int Id {get;set;}
    [XmlAttribute("description")]
    public string Description {get;set;}
    [XmlAttribute("type")]
    public string Type {get;set;}
    [XmlText]
    public string Filename {get;set;}
}

Note in particular the use of different attributes for different meanings. Verified (after fixing the closing element of your xml):

string xml = @"..."; // your xml, but fixed

Elements root;
using(var sr = new StringReader(xml))
using(var xr = XmlReader.Create(sr)) {
    root = (Elements) new XmlSerializer(typeof (Elements)).Deserialize(xr);
}
string filename = root.Items[0].Files[0].Filename; // the PDF

Upvotes: 0

Related Questions