0

I have string variable like xml structure:

string str = "<people><person><FirstName>Daniel</FirstName><LastName>Wylie</LastName></person>";

It has 1 node only. I need to convert it to my new model. I converted it to xml firstly like this:

 XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.LoadXml(xmlquery);

Now I need to move FirstName and LastName values from xml to following model:

public class Person 
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
}

How can I do this?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • I noticed your string 'str' does not have a closing '' tag, is that intentional? If you want to load XML and access the contents in an object model, you may want to look at using LINQ or XmlSerializer (http://stackoverflow.com/questions/14641646/xml-mapping-to-objects-without-attributes-in-c-sharp) – AFKAP Sep 04 '13 at 15:04

1 Answers1

0

Use XmlSerializer

But because your xml contain tag. Then create a class People for deserialization

public class People
{
    public List<Person> persons;
}

Then try:

XmlSerializer serial = new XmlSerializer(People.GetType());
//Convert yuor string to TextReader
using (TextReader reader = new StringReader(yourstring))
{
    People mans = serial.Deserialize(reader);
    Person man;
    if(mans.Count > 0)
        man = mans[0];
}
Fabio
  • 31,528
  • 4
  • 33
  • 72