gpt4 book ai didi

C# XML 序列化

转载 作者:数据小太阳 更新时间:2023-10-29 02:21:16 25 4
gpt4 key购买 nike

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

第一部分“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>

如果我不需要页眉区域,我知道该怎么做。我目前只是使用 xmlwriter 来创建它,但我想改为将对象序列化为 xml。

最佳答案

您需要根才能拥有有效的 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",
Category = "nature",
Description = "blah blah"
},
}
};

var serializer = new XmlSerializer(myData.GetType());
serializer.Serialize(Console.Out, myData);
}
}

关于C# XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5392469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com