I have an XML string which has the following structure:
<Element>
<Property1>Something</Propert1>
<Property2>SomethingElse</Property2>
</Element>
<Element>
<Property1>Something2</Propert1>
<Property2>SomethingElse2</Property2>
</Element>
I would like to serialize this to a List<Element>.
I use this code:
XmlSerializer xd = new XmlSerializer(typeof(T));
XDocument xdoc = XDocument.Parse(xmlStringToDesirialize);
T deserializedObject = xd.Deserialize(xdoc.CreateReader()) as T;
Where T is List<Element>. I get an exception saying There are multiple root elements. I understand why this is, but I`m not sure what to do about it.
I was thinking that adding a psudo-root element, like <Elements> might be a good solution, but I don't know how I would go about adding it to the XML document I already have.
Or maybe there is an alternative solution altogether.
EDIT: For completeness I am adding code for the full solution I needed for deserialization, in case anyone needs it.
I created a class:
[XmlRoot("myRoot", Namespace = "")]
public class MyRoot
{
[XmlElement("Element", Namespace = "{The xmlns of the actual class}")]
public List<Element> Elements {get; set;}
public MyRoot()
{
Elements = new List<Element>();
}
}
Then I deserialize to this class after adding the tags as suggested by @Richard. Hope this can help someone.