如果这是你想要的:
<ArrayOfB>
<b>
<a>Name</a>
</b>
<b>
<a>Age</a>
</b>
</ArrayOfB>
那么这应该工作。
public class XMLPlayground
{
public void Play()
{
List<b> list = new List<b>()
{
new b() {a = "Name"},
new b() {a = "Age"},
};
string str = SerializeToString(list);
Console.WriteLine(str);
}
private string SerializeToString(object o)
{
if (o == null) return "";
var xs = new XmlSerializer(o.GetType());
XmlSerializerNamespaces tellTheSeriliserToIgnoreNameSpaces = new XmlSerializerNamespaces();
tellTheSeriliserToIgnoreNameSpaces.Add(String.Empty, String.Empty);
XmlWriterSettings tellTheWriterToOmitTheXmlDeclaration = new XmlWriterSettings { OmitXmlDeclaration = true };
using (StringWriter writer = new StringWriter())
{
using (var xw = XmlWriter.Create(writer, tellTheWriterToOmitTheXmlDeclaration))
{
xs.Serialize(xw, o, tellTheSeriliserToIgnoreNameSpaces);
return writer.ToString();
}
}
}
}
[Serializable]
public class b
{
public string a { get; set; }
}
这是您想要实现的目标的一些见解,但对我来说,解决方案看起来相当深奥。您可能想尝试使用 XmlTextReader 的 SAX 方法并即时构建您的对象。
C# Xml序列化、集合和根元素