我有以下 xml 格式:
<FavouriteSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Customer>
<ID>12</ID>
<ID>2</ID>
<ID>5</ID>
</Customer>
<Supplier>
<ID>158</ID>
<ID>23</ID>
<ID>598</ID>
</Supplier>
</FavouriteSettings>
============================================= ==============
我将有一个像下面这样的类
class FavouriteList
{
public string Name; // this name will be "Customer" and "Supplier"
public List<int> aList; // to store those "ID" value
}
Class FavouriteSettings
{
public List<FavouriteList> bigList;
}
我必须做什么或更改什么才能使此类与 XMLSerializer 一起工作以生成类似该格式的 XML 文件并反序列化回列表和类作为 FavouriteList?
最佳答案
XmlSerializer
旨在将您的对象直接转换为 xml;您可以使用IXmlSerializable
,但很少有人值得这样做。您最好创建反射(reflect) xml 结构的对象。或者,更简单 - 使用 xsd 为您完成:
xsd example.xml
xsd example.xsd /classes
或者我怀疑下面的方法可行(未测试):
using System.Collections.Generic;
using System.Xml.Serialization;
public class FavoriteSettings
{
[XmlArray("Customer")]
[XmlArrayItem("ID")]
public List<int> Customers { get; set; }
[XmlArray("Supplier")]
[XmlArrayItem("ID")]
public List<int> Suppliers { get; set; }
}
特别是;如果您希望元素名称(“Customer”等)根据数据(“Name”等)而变化 - 除非您使用 IXmlSerializable
,否则它不会 hapopen ,或者使用 XDocument
(或类似的)自己编写。对于像这样的简单数据,也许 XDocument
是一个可行的选择?但是你会做很多额外的工作,尤其是在反序列化过程中。
这是一个通过 LINQ-to-XML 使用您的现有类的示例:
static class Program
{
static void Main() {
var favs = new FavouriteSettings
{
bigList = new List<FavouriteList>
{
new FavouriteList {
Name = "Customer",
aList = new List<int>{
12,2,5
}
}, new FavouriteList {
Name = "Supplier",
aList = new List<int>{
158, 23, 598
}
}
}
};
var el = new XElement("FavoriteSettings",
from fav in favs.bigList
select new XElement(fav.Name,
from item in fav.aList
select new XElement("ID", item)));
string xml = el.ToString();
Console.WriteLine(xml);
el = XElement.Parse(xml);
favs = new FavouriteSettings
{
bigList = new List<FavouriteList>(
from outer in el.Elements()
select new FavouriteList
{
Name = outer.Name.LocalName,
aList = new List<int>(
from id in outer.Elements("ID")
select (int)id
)
})
};
}
}
关于c# - 如何为 XML 序列化程序创建一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1501863/