I have the following XML
<?xml version="1.0" encoding="UTF-16" standalone="no"?>
<Sites>
<Site>
<Code>TWTR</Code>
<Name>twitter.com</Name>
</Site>
<Site>
<Code>FB</Code>
<Name>facebook.com</Name>
</Site>
<Site>
<Code>SO</Code>
<Name>stackoverflow.com</Name>
</Site>
</Sites>
This is the code:
public class Program
{
static void Main(string[] args)
{
var fs = new FileStream(@"D:empSites.xml", FileMode.Open);
var serializer = new XmlSerializer(typeof(List<Site>));
var instance = (List<Site>)serializer.Deserialize(fs);
}
}
[XmlRoot("Sites")]
public class Site
{
public string Code { get; set; }
public string Name { get; set; }
}
The exception I get is: <Sites xmlns=''> was not expected.
. The reason for this error is usually, when I don't define an XmlRoot for the XmlSerializer
. But as you can see, I did that by decorating the class Site
with the XmlRootAttribute
To complete my confusion, the following trick works:
Replace
var serializer = new XmlSerializer(typeof(List<Site>));
with
var serializer = new XmlSerializer(typeof(List<Site>), new XmlRootAttribute("Sites"));
Am I missing something?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…