Deserialize XML

倾然丶 夕夏残阳落幕 提交于 2019-12-25 02:26:09

问题


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. ;-)


回答1:


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

        }
    }
}



回答2:


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


来源:https://stackoverflow.com/questions/9257746/deserialize-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!