c# xml serialization extra root node
I have a collection that I want to serialize to an xml document. The class is开发者_StackOverflow中文版:
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?
[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
)
load your xml in to XmlDocument
xmlDoc.LoadXml(StrXML);
xmlDoc.SelectSingleNode("/Contacts/contacts")
I hope this will help you
精彩评论