2

I am designing my class model. The serialized message of the class model needs to be in this format:

<?xml version="1.0" encoding="UTF-8" ?>
<Request>
  <Name>TesterScript</Name>
  <ID>CD_20110628133820576</ID>
  <Type>
    <ItemId>191_20110628T133821</ItemId>
    <ShopId>MyBCShop</ShopId>
    <MessageXml>
    <ChildMessage>
      This is my message
    </ChildMessage>
    </MessageXml>
  </Type>
  <SentTime>2011-06-30T15:27:06-07:00</SentTime>
</Request>

How would I design the classes? Also what should be the best way to serialize the suggested class model to above XML message? I am thinking of using:

// Serialize the request
XmlSerializer xs = new XmlSerializer(typeof(Request));
StringWriter sw = new StringWriter();
xs.Serialize(sw, dispatchRequest);
string xml = sw.ToString();
return new xml;

Is this the most suitable way?

dbc
  • 104,963
  • 20
  • 228
  • 340
InfoLearner
  • 14,952
  • 20
  • 76
  • 124

2 Answers2

3

If you already have the schema, I would just use xsd.exe to generate the class. It'll come already marked up as serializable and you won't really have to do anything beyond calling the base XmlSerializer (as you're doing in your second snippet, more or less.)

AllenG
  • 8,112
  • 29
  • 40
1

I hope my solution is useful ....

The xml content (i think there is something wrong in your post...)

<?xml version="1.0" encoding="utf-8" ?>
<Request>
  <Name>TesterScript</Name>
  <ID>CD_20110628133820576</ID>
  <Type>
    <ItemId>191_20110628T133821</ItemId>
    <ShopId>BARCGB2L</ShopId>
    <MessageXml>
      <ChildMessage>
        This is my message
      </ChildMessage>
    </MessageXml>
  </Type>
  <SentTime>2011-06-30T15:27:06-07:00</SentTime>
</Request>

The class :

[XmlRoot("Request")]
public class SampleClass
{
    public string Name { get; set; }
    public string ID { get; set; }
    [XmlElement("Type")]
    public SubClass SC { get; set; }
    public string SentTime { get; set; }

    public class SubClass
    {
        public string ItemId { get; set; }
        public string ShopId { get; set; }
        [XmlElement("MessageXml")]
        public Sub2Class SC2 { get; set; }

        public class Sub2Class
        {
            public string ChildMessage { get; set; }
        }
    }
}

The Deserialize method:

public static T DeserializeForXml<T>(string filePath)
    {
        XmlSerializer selializer = new XmlSerializer(typeof(T));
        using (Stream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            return (T)selializer.Deserialize(fs);
        }
    }

How to use ?

SampleClass sc = Utility.DeserializeForXml<SampleClass>("test.xml");
shenhengbin
  • 4,236
  • 1
  • 24
  • 33