4

Here's a code example:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

...

static void Main() 
{
    Person[] persons = new Person[] 
    {
        new Person{ FirstName = "John", LastName = "Smith"},
        new Person{ FirstName = "Mark", LastName = "Jones"},
        new Person{ FirstName= "Alex", LastName="Hackman"}
    };

    XmlSerializer xs = new XmlSerializer(typeof(Person[]), "");

    using (FileStream stream = File.Create("persons-" + Guid.NewGuid().ToString().Substring(0, 4) + ".xml")) 
    {
        xs.Serialize(stream, persons);
    }
}

Here's the output:

<?xml version="1.0"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <FirstName>John</FirstName>
    <LastName>Smith</LastName>
  </Person>
  <Person>
    <FirstName>Mark</FirstName>
    <LastName>Jones</LastName>
  </Person>
  <Person>
    <FirstName>Alex</FirstName>
    <LastName>Hackman</LastName>
  </Person>
</ArrayOfPerson>

Here's a question. How to get rid of root element and render persons just like this:

<?xml version="1.0"?>
<Person>
  <FirstName>John</FirstName>
  <LastName>Smith</LastName>
</Person>
<Person>
  <FirstName>Mark</FirstName>
  <LastName>Jones</LastName>
</Person>
<Person>
  <FirstName>Alex</FirstName>
  <LastName>Hackman</LastName>
</Person>

Thanks!

the_V
  • 801
  • 3
  • 12
  • 21

2 Answers2

6

That's a malformed XML you want, not possible to obtain it via XmlSerializer, but you can change ArrayOfPersno element name to smothing else:

example:

XmlSerializer xs = new XmlSerializer(typeof(Person[]),
                                     new XmlRootAttribute("Persons"));

will give you:

<?xml version="1.0"?>
<Persons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <FirstName>John</FirstName>
    <LastName>Smith</LastName>
  </Person>
  ...
manji
  • 47,442
  • 5
  • 96
  • 103
  • With this approach, the `XmlSerializer` must be statically cached and reused to avoid a severe memory leak, see [Memory Leak using StreamReader and XmlSerializer](https://stackoverflow.com/q/23897145/3744182) for details. – dbc Sep 02 '18 at 15:50
2

IMO you should use a top-level object, I.e.

[XmlRoot("whatever")]
public class Foo {
    [XmlElement("Person")]
    public List<Person> People {get;set;}        
}

Which should serialize as a "whatever" element with multiple "Person" sub-elements.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900