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!
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>
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With