我想在C#中序列化/反序列化xml文档,例如:
<library>
<my.books genre =""classic"">
<book title = ""1984"" author=""George Orwell"" />
<book title = ""Robinson Crusoe"" author=""Daniel Defoe"" />
<book title = ""Frankenstein"" author=""Mary Shelly"" />
</my.books>
</library>";
有两件重要的事情:
元素“ my.books”必须具有自定义名称(而不是属性名称)
my.books元素必须具有属性(“体裁”)。
这是我的代码(示例在https://dotnetfiddle.net/bH5WVX上):
using System;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Serialization;
using System.IO;
public class Program
{
public static void Main()
{
Library lib = new Library(myBooks: new MyBooks(
genre: "classic",
booklist: new List<Book>{
new Book("1984", "George Orwell"),
new Book("Robinson Crusoe", "Daniel Defoe"),
new Book("Oliver Twist", "Mary Shelly"),
}));
XmlSerializer formatter = new XmlSerializer(typeof(Library));
using (StringWriter sw = new StringWriter())
{
formatter.Serialize(sw, lib);
Console.Write(sw.ToString());
}
输出为:
<library>
<MyBooks genre="classic">
<book title="1984" author="George Orwell" />
<book title="Robinson Crusoe" author="Daniel Defoe" />
<book title="Oliver Twist" author="Mary Shelly" />
</MyBooks>
</library>
唯一的问题是我不能强制元素“ MyBooks”使用名称“ my.books”
我仅找到有关此主题的一篇相关文章-http : //www.codemeit.com/xml/c-xmlserializer-add-an-attribute-to-an-array-element.html,它建议使用“ XmlType”属性在课堂上,但在这里不起作用。
有什么方法可以在此元素上应用自定义名称属性吗?
相关分类