I'm trying to deserialize a simple XML, but it Always returns null to my object.
XML
<ns0:Customer xmlns:ns0="http://myNameSpace.Customer">
<Company>001</Company>
<Division>003</Division>
</ns0:Customer>
CLASS
[XmlRoot(ElementName = "Customer", Namespace = "http://myNameSpace.Customer")]
public class Customer
{
[XmlElement(ElementName = "Company")]
public string Company { get; set; }
[XmlElement(ElementName = "Division")]
public string Division { get; set; }
}
CODE
File.AppendAllText(fileName, string.Format("Polling at {0}\n", DateTime.Now.ToString("o")));
XmlSerializer serializer = new XmlSerializer(typeof(Customer));
using (FileStream fileStream = new FileStream(PlatformServices.Default.Application.ApplicationBasePath
+ @"\Customers\Customer.xml", FileMode.Open))
{
var customers = ((Customer)serializer.Deserialize(fileStream));
}
RESULT
Any ideas ?
Your containing element does not define a default namespace, so the default namespace of the document is an empty string.
This means that <Company>
and <Division>
don't have the same namespace as the containing element, and inherit the default namespace ""
.
Your example will work if you rewrite the attributes to take this into account:
[XmlRoot(ElementName = "Customer", Namespace = "http://myNameSpace.Customer")]
public class Customer
{
[XmlElement(ElementName = "Company", Namespace = "")]
public string Company { get; set; }
[XmlElement(ElementName = "Division", Namespace = "")]
public string Division { get; set; }
}
as is demonstrated below:
var xmlStr = @" <ns0:Customer xmlns:ns0=""http://myNameSpace.Customer"">
<Company>001</Company>
<Division>003</Division>
</ns0:Customer>";
var ms = new MemoryStream(Encoding.UTF8.GetBytes(xmlStr));
XmlSerializer serializer = new XmlSerializer(typeof(Customer));
var customer = ((Customer)serializer.Deserialize(ms));
//yay. fully populated
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.