将XML数据转换为C#类

时间:2018-08-19 07:16:21

标签: c# xml asp.net-core

我的项目是Asp.net Core
我想将XML数据转换为C#类,XML数据有一个节点PersonelInfo,我尝试读取XML,但是代码不起作用。 我该如何解决此代码?我怎么了?

var xmlGetDetailsUser = new XmlDocument();
xmlGetDetailsUser.LoadXml(await responseMessageGetDetailsUser.Content.ReadAsStringAsync());
using (StringReader reader = new StringReader(xmlGetDetailsUser.InnerXml))
{
    try
    {
        PersonelInfo data = (PersonelInfo)(serializer.Deserialize(reader));
    }
    catch (System.Exception e)
    { }
}

public class PersonelInfo
{
  public string PersonelCode { get; set; }
  public string Email { get; set; }
}

xmlGetDetailsUser.InnerXml具有此值:

<?xml version=\"1.0\" encoding=\"utf-8\"?>
<ArrayOfPersonelInfo xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"sample url .....\">
    <PersonelInfo>
        <PersonelCode>99999</PersonelCode>    
        <Email>test@test.com</Email>        
    </PersonelInfo>
</ArrayOfPersonelInfo>

运行程序时,在try catch中显示此异常

  

XML出错

2 个答案:

答案 0 :(得分:3)

您应该为XmlSerializer设置名称空间,并将其类型更改为List<PersonelInfo>

尝试一下:

XmlSerializer serializer = new XmlSerializer(typeof(List<PersonelInfo>), "sample url ....");
            XmlReaderSettings settings = new XmlReaderSettings();
            using (StringReader textReader = new StringReader(await responseMessageGetDetailsUser.Content.ReadAsStringAsync()))
            {
                using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
                {
                    var data = (List<PersonelInfo>)serializer.Deserialize(xmlReader);
                }
            }

答案 1 :(得分:0)

我找到了答案,但是 似乎不是将XML转换为C#的好方法 您如何改进此代码?

var xmlGetDetailsUser = new XmlDocument();
xmlGetDetailsUser.LoadXml(await responseMessageGetDetailsUser.Content.ReadAsStringAsync());
var result = xmlGetDetailsUser.GetElementsByTagName("PersonelInfo");
XmlSerializer serializer = new XmlSerializer(typeof(PersonelInfo));
var personelInfo = new PersonelInfo();
personelInfo.PersonelCode = result.Item(0)["PersonelCode"].InnerText;
personelInfo.Email = result.Item(0)["Email"].InnerText;