How do I serialize an object to xml but not have it be the root element of the xml document

Posted by mezoid on Stack Overflow See other posts from Stack Overflow or by mezoid
Published on 2010-05-26T08:43:05Z Indexed on 2010/05/26 8:51 UTC
Read the original article Hit count: 461

Filed under:
|
|

I have the following object:

public class MyClass
{
    public int Id { get; set;}
    public string Name { get; set; }
}

I'm wanting to serialize this to the following xml string:

<MyClass>
    <Id>1</Id>
    <Name>My Name</Name>
</MyClass>

Unfortunately, when I use the XMLSerializer I get a string which looks like:

<?xml version="1.0" encoding="utf-8"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">  
    <Id>1</Id>
    <Name>My Name</Name>
</MyClass>

I'm not wanting MyClass to be the root element the document, rather I'm eventually wanting to add the string with other similar serialized objects which will be within a larger xml document.

i.e. Eventually I'll have a xml string which looks like this:

<Classes>
    <MyClass>
        <Id>1</Id>
        <Name>My Name</Name>
    </MyClass>
    <MyClass>
        <Id>1</Id>
        <Name>My Name</Name>
    </MyClass>
</Classes>"

My first thought was to create a class as follows:

public class Classes
{
    public List<MyClass> MyClasses { get; set; }
}

...but that just addes an additional node called MyClasses to wrap the list of MyClass....

My gut feeling is that I'm approaching this the wrong way and that my lack of experience with creating xml files isn't helping to point me to some part of the .NET framework or some other library that simplifies this.

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml