我正在设计我的班级模型。类模型的序列化消息需要采用以下格式:
<?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>
我如何设计课程? 另外,将建议的类模型序列化为上述XML消息的最佳方法是什么?我正在考虑使用:
// Serialize the request
XmlSerializer xs = new XmlSerializer(typeof(Request));
StringWriter sw = new StringWriter();
xs.Serialize(sw, dispatchRequest);
string xml = sw.ToString();
return new xml;
这是最合适的方式吗?
答案 0 :(得分:3)
如果您已经拥有架构,我只需使用xsd.exe
来生成该类。它已被标记为可序列化,除了调用基础XmlSerializer
之外你不会做任何事情(正如你在第二个片段中所做的那样,或多或少。)
答案 1 :(得分:1)
我希望我的解决方案很有用......
xml内容(我认为你的帖子有问题......)
<?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>
班级:
[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; }
}
}
}
反序列化方法:
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);
}
}
如何使用?
SampleClass sc = Utility.DeserializeForXml<SampleClass>("test.xml");