[英]XML returns NULL on XmlSerializer Deserialize DotNet Core C# (Console App)
I know this question is not new, but after searching for quite while, I decided to ask for help here.我知道这个问题并不新鲜,但经过一段时间的搜索,我决定在这里寻求帮助。 My XML deserialization is always null and I would like your thoughts on my code.
我的 XML 反序列化始终是 null ,我希望您对我的代码有想法。
private static bool MyJson(string mxl)
{
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Client";
xRoot.IsNullable = true;
var serializer = new XmlSerializer(typeof(MyDTO), xRoot);
MyDTO result;
using (TextReader reader = new StreamReader(xml))
{
result = serializer.Deserialize(reader) as MyDTO;
}
...
}
My XML我的 XML
<Client>
<References>
<Reference>TE01234</Reference>
</References>
<Intro>
<Name>Test</Name>
</Intro>
<Details>
<Claimant>
<Title>Mr</Title>
<FirstName>Cxxx</FirstName>
<Surname>Msyy</Surname>
</Claimant>
<Claimant2>
<Title2>Mrs</Title2>
<FirstName2>Xmsxx</FirstName2>
<Surname2>Cktol</Surname2>
</Claimant2>
</Details>
</Client>
My Model我的 Model
public class MyDTO
{
public string Reference {get;set;}
public string Name {get;set;}
public string Title {get;set;}
public string FirstName {get;set;}
public string Surname {get;set;}
public string Title2 {get;set;}
public string FirstName2 {get;set;}
public string Surname2 {get;set;}
}
The 'result;结果; is always null.
始终为 null。
Thanks for your help.谢谢你的帮助。
Use xml Linq:使用 xml Linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<MyDTO> dtos = doc.Descendants("Client").Select(x => new MyDTO()
{
Reference = (string)x.Descendants("Reference").FirstOrDefault(),
Name = (string)x.Descendants("Name").FirstOrDefault(),
Title = (string)x.Descendants("Title").FirstOrDefault(),
FirstName = (string)x.Descendants("FirstName").FirstOrDefault(),
Surname = (string)x.Descendants("Surname").FirstOrDefault(),
Title2 = (string)x.Descendants("Title2").FirstOrDefault(),
FirstName2 = (string)x.Descendants("FirstName2").FirstOrDefault(),
Surname2 = (string)x.Descendants("Surname2").FirstOrDefault()
}).ToList();
}
}
public class MyDTO
{
public string Reference {get;set;}
public string Name {get;set;}
public string Title {get;set;}
public string FirstName {get;set;}
public string Surname {get;set;}
public string Title2 {get;set;}
public string FirstName2 {get;set;}
public string Surname2 {get;set;}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.