Serializzazione XML di array C #
-
02-07-2019 - |
Domanda
Ho riscontrato un problema con la serializzazione XML di C #. L'output del serializzatore è incoerente tra Win32 normale e WinCE (ma sorprendentemente WinCE ha l'output del correttore IMO). Win32 ignora semplicemente l'attributo Class2 XmlRoot (" c2 ")
.
Qualcuno sa come ottenere l'output simile a WinCE su Win32 (perché non voglio che i tag XML abbiano il nome della classe della classe di serializzazione).
Codice test:
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);
}
}
}
}
XML previsto (WinCE genera questo):
<?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 (sembra essere la versione sbagliata):
<?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>
Soluzione
Prova [XmlArrayItem (" c2 ")]
[XmlRoot("c1")]
public class Class1
{
[XmlArray("items")]
[XmlArrayItem("c2")]
public Class2[] Items;
}
o [XmlType (" c2 ")]
[XmlType("c2")]
public class Class2
{
[XmlAttribute("name")]
public string Name;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow