gpt4 book ai didi

c# - XmlSerializer 添加属性

转载 作者:行者123 更新时间:2023-11-30 15:30:15 24 4
gpt4 key购买 nike

我有这个项目类:

public class Movie
{
public string VideoId { get; set; }
public string Title { get; set; }
}

我有List<Movie>这个项目,我使用这个代码序列化到 xml 文件:

string fileName = index + ".xml";
string serializationFile = Path.Combine(dir, fileName);

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

using (var writer = XmlWriter.Create(serializationFile, settings))
{
var serializer = new XmlSerializer(typeof(List<Movie>));
serializer.Serialize(writer, tmpList);
}

这是结果:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMovie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Movie>
<VideoId>MyId</VideoId>
<Title>MyTitle</Title>
</Movie>
<Movie>
<VideoId>MyId1</VideoId>
<Title>MyTitle1</Title>
</Movie>
<Movie>
<VideoId>MyId2</VideoId>
<Title>MyTitle2</Title>
</Movie>
<Movie>
<VideoId>MyId3</VideoId>
<Title>MyTitle3</Title>
</Movie>
</ArrayOfMovie>

并且可以将属性添加到 ArrayOfMovie节点,像这样:

<ArrayOfMovie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" customattribute='Yes'>

最佳答案

是的,您可以使用 XmlAttribute attribute 来做到这一点.为此,您需要定义自定义属性。它带有代表数组(嵌套在根节点中)的另一个类的价格。如果您对此添加没问题,那么解决方案可能如下所示:

public class ArrayOfMovie
{
// define the custom attribute
[XmlAttribute(AttributeName="CustomAttribute")]
public String Custom { get; set; }
// define the collection description
[XmlArray(ElementName="Items")]
public List<Movie> Items { get; set; }
}

public class Movie
{
public string VideoId { get; set; }
public string Title { get; set; }
}

然后像您已经做的那样创建、填充和序列化 - 一件新的事情是填充您的自定义属性:

// create and fill the list
var tmpList = new List<Movie>();
tmpList.Add(new Movie { VideoId = "1", Title = "Movie 1" });
tmpList.Add(new Movie { VideoId = "2", Title = "Movie 2" });
// create the collection
var movies = new ArrayOfMovie
{
Items = tmpList,
Custom = "yes" // fill the custom attribute
};
// serialize
using (var writer = XmlWriter.Create(serializationFile, settings))
{
var serializer = new XmlSerializer(typeof(ArrayOfMovie));
serializer.Serialize(writer, movies);
}

XML 输出如下所示:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMovie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
CustomAttribute="yes">
<Items>
<Movie>
<VideoId>1</VideoId>
<Title>Movie 1</Title>
</Movie>
<Movie>
<VideoId>2</VideoId>
<Title>Movie 2</Title>
</Movie>
</Items>
</ArrayOfMovie>

关于c# - XmlSerializer 添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22435755/

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