您可能可以编写一个简单的类,例如我使用这样的 Speech 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace StackOverflowSamples
{
[Serializable]
public class Speech
{
public Speech()
{
this.Items = new List<LanguageItem>();
}
[XmlArray]
public List<LanguageItem> Items;
}
[Serializable]
public class LanguageItem
{
[XmlAttribute]
public string Language { get; set; }
[XmlAttribute]
public int Id { get; set; }
}
}
可以使用以下代码简单地序列化:
// use built in serialization mechanism
XmlSerializer mySerializer = new XmlSerializer(typeof(Speech));
// Writing the file requires a TextWriter.
TextWriter writer = new StreamWriter("test.xml");
var speech = new Speech();
var lang1 = new LanguageItem() { Id = 1, Language = "English", };
var lang2 = new LanguageItem() { Id = 2, Language = "Slovenian", };
speech.Items.Add(lang1);
speech.Items.Add(lang2);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
mySerializer.Serialize(writer, speech, ns);
writer.Close();
在这里产生这样的XML:
<?xml version="1.0" encoding="utf-8"?>
<Speech>
<Items>
<LanguageItem Language="English" Id="1" />
<LanguageItem Language="Slovenian" Id="2" />
</Items>
</Speech>