Mohammad Daliri
Mohammad Daliri

Reputation: 1396

Convert XML data to C# class

My project is Asp.net Core
I want to convert XML data to C# class,XML data has a node PersonelInfo I try to read XML but It's code not working. How can I solve this code? What is my problem?

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)
    { }
}

class

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

xmlGetDetailsUser.InnerXml has this value :

<?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>[email protected]</Email>        
    </PersonelInfo>
</ArrayOfPersonelInfo>

when run my program show this exception in try catch

There is an error in XML

Upvotes: 0

Views: 2849

Answers (2)

Mohammad Daliri
Mohammad Daliri

Reputation: 1396

I Found the answers but It seems is not a good way for convert XML to C# What do you think of improving this code?

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;

Upvotes: 0

Hossein
Hossein

Reputation: 3113

You should set namespace for XmlSerializer and change type of it to List<PersonelInfo>.

Try this:

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);
                }
            }

Upvotes: 4

Related Questions