2

I've been playing around with the xml serialization for a while and I've hit a problem with serializing the a list collection. I want to serialize a list collection without the upper element wrapping around it. See example below:

Result serialization:

<?xml version="1.0" encoding="utf-8" ?>
<Person>
  <Name>John</Name>
  <AddressLine>
    <string>Line 1</string>
    <string>Line 2</string>
    <string>Line 3</string>
  </AddressLine>
  <Telephone>123456789</Telephone>
</Person>

The serialization I want to output is:

<?xml version="1.0" encoding="utf-8" ?>
<Person>
  <Name>John</Name>
  <AddressLine>Line 1</AddressLine>
  <AddressLine>Line 2</AddressLine>
  <AddressLine>Line 3</AddressLine>
  <Telephone>123456789</Telephone>
</Person>

I have tried setting different the attributes to my class I'm serializaing from but I can't seem to get anywhere with it. If anyone could show me what attributes I need to use to get my xml serialization to look like the ouput xml I want that would be greatly appreciated.

Cheers!

madness800
  • 181
  • 1
  • 2
  • 13

1 Answers1

4
[Serializable]
public class Person
{
    public string Name { get; set; }

    [XmlElement]
    public List<string> AddressLine { get; set; }
}

Produces desired output:

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>John</Name>
  <AddressLine>1</AddressLine>
  <AddressLine>2</AddressLine>
  <AddressLine>3</AddressLine>
</Person>
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125