C# Array XML Serialization

为君一笑 提交于 2019-12-28 14:01:39

问题


I found a problem with the XML Serialization of C#. The output of the serializer is inconsistent between normal Win32 and WinCE (but surprisingly WinCE has the IMO correcter output). Win32 simply ignores the Class2 XmlRoot("c2") Attribute.

Does anyone know a way how to get the WinCE like output on Win32 (because i don't want the XML tags to have the class name of the serialization class).

Test Code:

using System;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleTest
{
    [Serializable]
    [XmlRoot("c1")]
    public class Class1
    {
        [XmlArray("items")]
        public Class2[] Items;
    }

    [Serializable]
    [XmlRoot("c2")]
    public class Class2
    {
        [XmlAttribute("name")]
        public string Name;
    }

    class SerTest
    {
        public void Execute()
        {
            XmlSerializer ser = new XmlSerializer(typeof (Class1));

            Class1 test = new Class1 {Items = new [] {new Class2 {Name = "Some Name"}, new Class2 {Name = "Another Name"}}};

            using (TextWriter writer = new StreamWriter("test.xml"))
            {
                ser.Serialize(writer, test);
            }
        }
    }
}

Expected XML (WinCE generates this):

<?xml version="1.0" encoding="utf-8"?>
<c1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <items>
    <c2 name="Some Name" />
    <c2 name="Another Name" />
  </items>
</c1>

Win32 XML (seems to be the wrong version):

<?xml version="1.0" encoding="utf-8"?>
<c1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <items>
    <Class2 name="Some Name" />
    <Class2 name="Another Name" />
  </items>
</c1>

回答1:


Try [XmlArrayItem("c2")]

[XmlRoot("c1")]
public class Class1
{
    [XmlArray("items")]
    [XmlArrayItem("c2")] 
    public Class2[] Items;
}

or [XmlType("c2")]

[XmlType("c2")]
public class Class2
{
    [XmlAttribute("name")]
    public string Name;
}


来源:https://stackoverflow.com/questions/126155/c-sharp-array-xml-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!