0
votes

How to serialize this XML string below to object?

Given XML Definition:

<Person>
    <Name>Jack</Name>
    <Address><Hotel>Merriot</Hotel></Address>
</Person>

Given Object Definition:

Public Class Person
{
    Public String Name;
    Public String Address;
}

So, basically after the serialization, I would have Person object with Name Property's value is "Jack" and Address Property's value is <Hotel>Merriot</Hotel>

Thanks for your kind advise in advance!

4

4 Answers

2
votes

You have to create different class for Adress, or implement IXmlSerializable

http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable%28v=vs.110%29.aspx#fbid=FpiOK3ZYdUD

and place your own method to split adress string (using [XmlIgnore] for current Adress)

1
votes
public class Person
{
    public string Name {get;set;}
    public Address Address {get;set;}
}

public class Address
{
   public string Hotel{get;set;}
}
1
votes

Why do you want the raw XML?

There are two ways if you really want to

  1. To keep Address as a string, Person class has to implement IXmlSerializable as said by @interneo but serializing yourself is difficult and error prone.

  2. A cleaner solution is to change the type of Address to one that also implements IXmlSerializable. That type is InnerXml in my sample

Sample:

public class Person
{
    public string Name { get; set; }
    public InnerXml Address { get; set; }
}

public class InnerXml : IXmlSerializable
{
    public string Content { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        Content = reader.ReadInnerXml();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        if (Content != null)
        {
            writer.WriteRaw(Content);
        }
    }
}

using (var testXmlReader = new StringReader(testXml))
{
    var serializer = new XmlSerializer(typeof(Person));
    var person = (Person)serializer.Deserialize(testXmlReader);

    Console.WriteLine(person.Address.Content); //outputs <Hotel>Merriot</Hotel>
}
0
votes
here the case is of nested Serializaton:
Better use following approach:

[Serializable]
public class person
{
public String Name;
public Address HotelAddress;
}

[Serializable ]
public class Address 
 {
  public string HotelName;
 }

Now deserlize the main Class u'll get instances for child class also.