XML将具有相同名称的多个元素序列化而没有名称空间

时间:2018-11-09 06:15:40

标签: c# .net xml xmlserializer

我有以下要尝试序列化的类。我有两个具有相同数据类型的数组。我知道,如果我们需要多个元素来具有相同的名称,则命名空间将有所不同。但是,有一种解决方法可以完全删除这些命名空间。

[XmlRoot]
public class Album
{
    public string Title { get; set; }
    public string Description { get; set;}
    public int CoverImgIndx { get; set; }
    [XmlElement(ElementName ="Element", Namespace ="www.image.com")]
    public Image[] Images { get; set; }
    [XmlElement(ElementName ="Element", Namespace ="www.cover.com")]
    public Image[] Cover { get; set; }

}

public class Image
{
    public int indx { get; set; }
    public string filepath { get; set; }
}

我正在使用XmlSerializer对此序列化。

public class Program
{
    public static void Main()
    {
        var album = new Album
        {
            Title = "Album Title",
            Description = "Some explanation.",
            CoverImgIndx = 2,
            Images = new Image[] {
                new Image { indx = 0, filepath = @"C:\Images\file1.jpg" },
                new Image { indx = 1, filepath = @"C:\Images\file2.png" },
                new Image { indx = 2, filepath = @"C:\Images\file3.jpg" }
            },
            Cover =  new Image[] {
                new Image { indx = 0, filepath = @"C:\Images\cover1.jpg" }
            }
        };

        XmlSerializer serializer = new XmlSerializer(typeof(Album));
        serializer.Serialize(Console.Out, album);
    }
}

我得到的输出是图像元素的命名空间。可以删除命名空间,而不必删除共享相同元素名称的Images和Cover。

<?xml version="1.0" encoding="utf-16"?>
<Album xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Title>Album Title</Title>
  <Description>Some explanation.</Description>
  <CoverImgIndx>2</CoverImgIndx>
  <Element xmlns="www.image.com">
    <indx>0</indx>
    <filepath>C:\Images\file1.jpg</filepath>
  </Element>
  <Element xmlns="www.image.com">
    <indx>1</indx>
    <filepath>C:\Images\file2.png</filepath>
  </Element>
  <Element xmlns="www.image.com">
    <indx>2</indx>
    <filepath>C:\Images\file3.jpg</filepath>
  </Element>
  <Element xmlns="www.cover.com">
    <indx>0</indx>
    <filepath>C:\Images\cover1.jpg</filepath>
  </Element>
</Album>

我正在寻找的输出

<?xml version="1.0" encoding="utf-16"?>
<Album xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Title>Album Title</Title>
  <Description>Some explanation.</Description>
  <CoverImgIndx>2</CoverImgIndx>
  <Element>
    <indx>0</indx>
    <filepath>C:\Images\file1.jpg</filepath>
  </Element>
  <Element>
    <indx>1</indx>
    <filepath>C:\Images\file2.png</filepath>
  </Element>
  <Element>
    <indx>2</indx>
    <filepath>C:\Images\file3.jpg</filepath>
  </Element>
  <Element>
    <indx>0</indx>
    <filepath>C:\Images\cover1.jpg</filepath>
  </Element>
</Album>

0 个答案:

没有答案