Patrick
Patrick

Reputation: 2790

c# xml serialization extra root node

I have a collection that I want to serialize to an xml document. The class is:

public class Contacts{
  public List<PendingContactDTO> contacts { get; set; } 
}

My main problem is that now my xml looks

<Contacts>
   <contacts>
       <..... all contacts>
   </contacts>
</Contacts>

The thing is, I want to look it like this:

   <contacts>
       <..... all contacts>
   </contacts>

Is there a way to this?

Upvotes: 4

Views: 1320

Answers (2)

Fahad Hussain
Fahad Hussain

Reputation: 1185

load your xml in to XmlDocument

xmlDoc.LoadXml(StrXML);
xmlDoc.SelectSingleNode("/Contacts/contacts")

I hope this will help you

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062650

[XmlRoot("contacts")]
public class Contacts{
    [XmlElement("contact")]
    public List<PendingContactDTO> contacts { get; set; } 
}

should give you:

<contacts>
     <contact...>...</contact>
     ...
     <contact...>...</contact>
</contacts>

(the XmlRootAttribute renames the Contacts to contacts; the XmlElementAttribute tells it to remove the extra layer for the collection node, naming each contact)

Upvotes: 6

Related Questions