[英]AspNet Core - Deserialize XML returns null
I'm trying to deserialize a simple XML, but it Always returns null to my object. 我正在尝试反序列化一个简单的XML,但是它总是向我的对象返回null。
XML 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. 您的contains元素未定义默认名称空间,因此文档的默认名称空间为空字符串。
This means that <Company>
and <Division>
don't have the same namespace as the containing element, and inherit the default namespace ""
. 这意味着<Company>
和<Division>
与包含元素的名称空间不同,并继承默认名称空间""
。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.