我遇到了下一个序列化问题。我有一个我要序列化的MyObject
类的列表,但不能在所需的视图中执行。问题如下。我有这个类结构:
[XmlRoot(ElementName = "response")]
public class Response : List<MyObject> {}
[XmlElement("myObject")]
public class MyObject { ... }
在序列化之后我得到了这个:
<response>
<myObject>
...
</myObject>
<myObject>
...
</myObject>
<myObject>
...
</myObject>
</response>
但我需要这个:
<response>
<myObejcts>
<myObject>
...
</myObject>
<myObject>
...
</myObject>
<myObject>
...
</myObject>
</myObejcts>
</response>
我可以以任何方式获得XML结构而不添加属性
public List<MyObject> {get; set;}
到Response
课程。我不能使用List
属性的原因是因为我使用了Entity Framework,在这种情况下,EF在数据库中添加了一些额外的不需要的表。
答案 0 :(得分:1)
您可以包装完整的Response对象,然后使用此对象进行序列化吗?
[XmlRoot("response")]
public class ResponseWrapper<T>
{
[XmlArray("MyObjects")]
[XmlArrayItem]
public List<T> Items { get; set; }
public ResponseWrapper()
{
}
public ResponseWrapper(List<T> items)
{
this.Items = items;
}
}
然后生成如下输出:
<?xml version="1.0"?>
<response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http:
//www.w3.org/2001/XMLSchema">
<MyObjects>
<MyObject>
<ID>1</ID>
<Name>Buck</Name>
</MyObject>
<MyObject>
<ID>2</ID>
<Name>Rogers</Name>
</MyObject>
<MyObject>
<ID>3</ID>
<Name>Flash</Name>
</MyObject>
<MyObject>
<ID>4</ID>
<Name>Gordon</Name>
</MyObject>
</MyObjects>
</response>
只是,它仍然需要你做一些额外的工作,是的:)
答案 1 :(得分:-1)
@Vsevywniy再次问好,虽然我仍然相信创建一个Wrapper类是实现这一目标的最佳方法。另一个选项可以是实现IXmlSerializable来控制序列化并添加自定义元素。我能够将您的类结构序列化为您期望的XML。请看下面的代码:
public class Program
{
public static void Main(string[] args)
{
var products = new MyObjects()
{
new MyObject() {Id = 1, Name = "Dell"},
new MyObject() {Id = 2, Name = "Sony"},
new MyObject() {Id = 3, Name = "HP"}
};
var serializeObject = SerializeObject<MyObjects>(products);
Console.WriteLine(serializeObject);
Console.ReadLine();
}
public static string SerializeObject<T>(Object data)
{
string result;
try
{
var xmlData = new MemoryStream();
var xmlEncodedData = new XmlTextWriter(xmlData, Encoding.UTF8);
var serial = new XmlSerializer(typeof(T));
serial.Serialize(xmlEncodedData, data);
xmlData.Position = 0;
var reader = new StreamReader(xmlData);
result = reader.ReadToEnd();
}
catch (Exception)
{
return string.Format("Error in return data");
}
return result;
}
}
[XmlRoot("Response")]
[Serializable]
public class MyObjects : List<MyObject>, IXmlSerializable
{
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("MyObjects");
foreach (var myObject in this)
{
new XmlSerializer(typeof(MyObject)).Serialize(writer, myObject);
}
writer.WriteEndElement();
}
}
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
}
}