c#XML序列化

mot*_*tai 3 c# xml xmlserializer

我想序列化这样的东西,其中有一个标题和一个正文.

第一部分"galleryData"是标题第二部分是"imageData" - 为图库中的每个图像重复

<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>
Run Code Online (Sandbox Code Playgroud)

如果我不需要标题区域,我会看到如何做到这一点.我目前只是使用xmlwriter来创建它,但我想将对象序列化为xml.

Dar*_*rov 6

您需要一个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; }
}
Run Code Online (Sandbox Code Playgroud)

然后只需创建此模型的实例并将其序列化为流:

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",
                    Category = "nature",
                    Description = "blah blah"
                },
            }
        };

        var serializer = new XmlSerializer(myData.GetType());
        serializer.Serialize(Console.Out, myData);
    }
}
Run Code Online (Sandbox Code Playgroud)