XmlSerializer添加属性

本文关键字:属性 添加 XmlSerializer | 更新日期: 2023-09-27 17:50:24

我有这个项目class:

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'>

XmlSerializer添加属性

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

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>

可以在序列化之后执行。代码框架如下所示:

    using (MemoryStream ms = new MemoryStream())
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        using (var writer = XmlWriter.Create(ms, settings))
        {
            var serializer = new XmlSerializer(typeof(List<Movie>));
            serializer.Serialize(writer, tmpList);
        }
        ms.Position = 0;
        XDocument doc = XDocument.Load(new XmlTextReader(ms));
        doc.Root.Add(new XAttribute("customAttribute", "Yes"));
        doc.Save(filename);
    }

您可能想要将List<Movie>封装在一个类中,然后将其序列化。如下所示

class Program
{        
    static void Main(string[] args)
    {
        string fileName = "abcd2.xml";
        string serializationFile = Path.Combine(@"C:'", fileName);
        List<Movie> tmpList = new List<Movie>();
        tmpList.Add(new Movie() { VideoId = "1", Title = "Hello" });
        tmpList.Add(new Movie() { VideoId = "2", Title = "ABCD" });
        MovieList list = new MovieList("Yes", tmpList);
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        using (var writer = XmlWriter.Create(serializationFile, settings))
        {
            var serializer = new XmlSerializer(typeof(MovieList));
            serializer.Serialize(writer, list);
        }
    }
}
public class MovieList
{
    private string custom;
    private List<Movie> movies;
    public MovieList() { }
    public MovieList(string custom, List<Movie> movies)
    {
        this.movies = movies;
        this.custom = custom;
    }
    [XmlAttribute]
    public string CustomAttribute
    {
        get { return this.custom; }
        set { this.custom = value; }
    }
    public List<Movie> Movies
    {
        get
        {
            return  movies;
        }
        set
        {
            this.movies = value;
        }
    }
}
public class Movie
{
    public string VideoId { get; set; }
    public string Title { get; set; }
}

代码可以改进很多。这只是一个示例片段。查看以下MSDN链接:http://msdn.microsoft.com/en-us/library/58a18dwa(v=vs.110).aspx