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!

2
  • 3
    You want an invalid XML! Where is the root node? Commented May 4, 2011 at 14:37
  • Agreed: that is not a well-formed XML document Commented May 4, 2011 at 14:39

2 Answers 2

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>
  ...
Sign up to request clarification or add additional context in comments.

1 Comment

With this approach, the XmlSerializer must be statically cached and reused to avoid a severe memory leak, see Memory Leak using StreamReader and XmlSerializer for details.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.