c#XML序列化
发布时间:2020-12-16 09:33:33 所属栏目:百科 来源:网络整理
导读:我想序列化这样的东西,其中有一个标题和一个正文. 第一部分“galleryData”是标题 第二部分是“imageData” – 为图库中的每个图像重复 galleryData titlesome title/title uuid32432322/uuid imagepathsome path/imagepath/galleryDataimageData titletitle
我想序列化这样的东西,其中有一个标题和一个正文.
第一部分“galleryData”是标题 <galleryData> <title>some title</title> <uuid>32432322</uuid> <imagepath>some path</imagepath> </galleryData> <imageData> <title>title one</title> <category>nature</category> <description>blah blah</description> </imageData> <imageData> <title>title two</title> <category>nature</category> <description>blah blah</description> </imageData> <imageData> <title>title three</title> <category>nature</category> <description>blah blah</description> </imageData> 如果我不需要标题区域,我会看到如何做到这一点.我目前只是使用xmlwriter来创建它,但我想将对象序列化为xml. 解决方法
您需要一个root才能拥有有效的XML.以下是模型外观的示例:
public class ImageData { [XmlElement("title")] public string Title { get; set; } [XmlElement("category")] public string Category { get; set; } [XmlElement("description")] public string Description { get; set; } } public class GalleryData { [XmlElement("title")] public string Title { get; set; } [XmlElement("uuid")] public string UUID { get; set; } [XmlElement("imagepath")] public string ImagePath { get; set; } } public class MyData { [XmlElement("galleryData")] public GalleryData GalleryData { get; set; } [XmlElement("imageData")] public ImageData[] ImageDatas { get; set; } } 然后只需创建此模型的实例并将其序列化为流: class Program { static void Main() { var myData = new MyData { GalleryData = new GalleryData { Title = "some title",UUID = "32432322",ImagePath = "some path" },ImageDatas = new[] { new ImageData { Title = "title one",Category = "nature",Description = "blah blah" },new ImageData { Title = "title two",} }; var serializer = new XmlSerializer(myData.GetType()); serializer.Serialize(Console.Out,myData); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |