以下是如何为定义如下的 Job / Person 类型实现它
public class Job
{
[XmlElement]
public int Id;
}
public class Person
{
[XmlElement]
public int Id;
}
要生成 JobResult Xml,
private static string GetJobResultXml()
{
var jobs = new Result<Job>();
jobs.Items.Add(new Job() { Id = 1 });
jobs.Items.Add(new Job() { Id = 2 });
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add("", "");
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.ConformanceLevel = ConformanceLevel.Auto;
xws.Indent = true;
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attr = new XmlAttributes();
attr.XmlRoot = new XmlRootAttribute("JobResult");
overrides.Add(jobs.GetType(), attr);
XmlAttributes attr1 = new XmlAttributes();
attr1.XmlElements.Add(new XmlElementAttribute("Job", typeof(Job)));
overrides.Add(jobs.GetType(), "Items", attr1);
StringBuilder xmlString = new StringBuilder();
using (XmlWriter xtw = XmlTextWriter.Create(xmlString, xws))
{
XmlSerializer serializer = new XmlSerializer(jobs.GetType(), overrides);
serializer.Serialize(xtw, jobs, xmlnsEmpty);
xtw.Flush();
}
return xmlString.ToString();
}
为了生成 PersonResult xml,您必须稍微修改上述方法以获得预期的结果,如下所示
private static string GetPersonResultXml()
{
var jobs = new Result<Person>();
jobs.Items.Add(new Person() { Id = 1 });
jobs.Items.Add(new Person() { Id = 2 });
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add("", "");
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.ConformanceLevel = ConformanceLevel.Auto;
xws.Indent = true;
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attr = new XmlAttributes();
attr.XmlRoot = new XmlRootAttribute("PersonResult");
overrides.Add(jobs.GetType(), attr);
XmlAttributes attr1 = new XmlAttributes();
attr1.XmlElements.Add(new XmlElementAttribute("Person", typeof(Person)));
overrides.Add(jobs.GetType(), "Items", attr1);
StringBuilder xmlString = new StringBuilder();
using (XmlWriter xtw = XmlTextWriter.Create(xmlString, xws))
{
XmlSerializer serializer = new XmlSerializer(jobs.GetType(), overrides);
serializer.Serialize(xtw, jobs, xmlnsEmpty);
xtw.Flush();
}
return xmlString.ToString();
}
我希望这有帮助。
有关使用 XmlAttributes 类的更多信息,请点击此链接
http://msdn.microsoft.com/en-us/library/sx1a4zea(v=vs.80).aspx