views:

7386

answers:

1

Hi, 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"&gt;
  <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"&gt;
  <items>
    <Class2 name="Some Name" />
    <Class2 name="Another Name" />
  </items>
</c1>
+8  A: 

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;
}
codemeit