C# XML deserialization problem
I have the following XML snippet:
<?xml version="1.0" encoding="utf-8"?>
<dmFiles>
<dmFile dmUpFileGuid=""
dmFileDescr="testcase01.pdf"
dmFileMetaType="main"
dmFileGuid=""
dmMimeType="pdf"
dmFormat="">
<dmEncodedContent></dmEncodedContent>
</dmFile>
</dmFiles>
When I try to deserialize it, nothing gets populated, my c# class is defined like this, please help me spot my logic flaw:
[Serializable]
public class dmFiles
{
public dmFile[] dmFile
{
get;
set;
}
}
public class dmFile
{
[XmlAttribute("dmUpFileGuid")]
public string dmUpFileGuid
{
get;
set;
}
[XmlAttribute("dmFileDescr")]
public string dmFileDescr
{
get;
set;
}
[XmlAttribute("dmFileMetaType")]
public string dmFileMetaType
{
get;
set;
}
[XmlAttribute("dmFileGuid")]
开发者_高级运维 public string dmFileGuid
{
get;
set;
}
[XmlAttribute("dmMimeType")]
public string dmMimeType
{
get;
set;
}
[XmlAttribute("dmFormat")]
public string dmFormat
{
get;
set;
}
[XmlElement]
public string dmEncodedContent
{
get;
set;
}
}
I expect the array is expecting two levels of elements; try:
[XmlElement("dmFile")]
public dmFile[] dmFile
{
get;
set;
}
(which tells it to use a single level of elements called "dmFile"
for the array contents)
btw, you can name your classes more naturally by adding attributes to control naming; for example:
[XmlRoot("dmFiles")] // don't normally need [Serializable]
public class FilesWrapper // whatever you want
{ ... }
For info, I tested it and it works fine:
using(XmlReader xr = XmlReader.Create(new StringReader(sampleXml))) {
XmlSerializer ser = new XmlSerializer(typeof(dmFiles));
dmFiles obj = (dmFiles)ser.Deserialize(xr);
// obj has 1 file, with all the correct properties set
}
精彩评论