Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rid of <ArrayOfClassname> root element when serializing array

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!

like image 668
the_V Avatar asked Feb 24 '23 07:02

the_V


2 Answers

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>
  ...
like image 99
manji Avatar answered Feb 26 '23 21:02

manji


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.

like image 23
Marc Gravell Avatar answered Feb 26 '23 21:02

Marc Gravell