Home > Net >  How to serialize duplicate XML elements into an array?
How to serialize duplicate XML elements into an array?

Time:09-21

I'm attempting to serialize some poorly formatted XML. I'm specifically having issues converting duplicate elements into an array.

In usual cases, something like this would serialize just fine

Class

public class Animal
{
    [XmlArray("Dogs")]
    [XmlArrayItem("Dog", typeof(Dog))]
    public Dog[] Dogs {get;set;}
}

XML

<Animals>
    <Dogs>
        <Dog>
            <Name>Spot</Name>
            <Age>5</Age>
        </Dog>
        <Dog>
            <Name>Spike</Name>
            <Age>2</Age>
        </Dog>
        <Dog>
            <Name>Arnold</Name>
            <Age>7</Age>
        </Dog>
    </Dogs>
</Animals>

In reality, the XML is structured as follows

<Animals>
    <Dog>
        <Name>Spot</Name>
        <Age>5</Age>
    </Dog>
    <Dog>
        <Name>Spike</Name>
        <Age>2</Age>
    </Dog>
    <Dog>
        <Name>Arnold</Name>
        <Age>7</Age>
    </Dog>
</Animals>

What's the easiest way I can serialize these properties into an array?

CodePudding user response:

It should work as described in https://docs.microsoft.com/en-us/dotnet/standard/serialization/controlling-xml-serialization-using-attributes#serializing-an-array-as-a-sequence-of-elements i.e.

[XmlElement(ElementName = "Dog")]
public Dog[] Dogs {get;set;}

CodePudding user response:

The question doesn't contain code of serializing method. Anyway, the XML markup described above should work when using the following serializing method:

public class Animals
{
    [XmlArray("Dogs")]
    [XmlArrayItem("Dog", typeof(Dog))]
    public Dog[] Dogs { get; set; }
}

public static string SerializeToXml(object o)
{          
    var ns = new XmlSerializerNamespaces(new[] { Ident=true, XmlQualifiedName.Empty });
    using (var stream = new StringWriter())
    using (var writer = XmlWriter.Create(stream, new XmlWriterSettings { OmitXmlDeclaration = true }))
    {
        var serializer = new XmlSerializer(typeof(Animals));
        serializer.Serialize(writer, o, ns);
        return stream.ToString();
    }
}

The test code

var animals = new Animals()
    {
        Dogs = new Dog[] { new Dog { Name = "dog1", Age = 6 }, new Dog { Name = "dog2", Age = 7 } }
    };

var xml = SerializeToXml(animals);

will produce the following XML:

<Animals>
  <Dogs>
    <Dog>
      <Name>dog1</Name>
      <Age>6</Age>
    </Dog>
    <Dog>
      <Name>dog2</Name>
      <Age>7</Age>
    </Dog>
  </Dogs>
</Animals>

For additional information see Serializing an Array of Objects.

  • Related