1

Given this XML:

<Items>
 <Item>a</Item>
 <Item>b</Item>
</Items>

How can I deserialize this using XmlSerializer? Either into an array of some custom type or simply into a string[].

I know this can be done if the innermost tags are called "string" but I'd like to keep a custom name.

1 Answer 1

6

Here's one way demonstrating using the XmlSerializer in LINQPad

void Main()
{
    using(var stream = new StringReader("<Items><Item>a</Item><Item>b</Item></Items>"))
    {
        var serializer = new XmlSerializer(typeof(Container));

        var items = (Container)serializer.Deserialize(stream);

        items.Dump();
    }
}

[XmlRoot("Items")]
public class Container
{
    [XmlElement("Item")]
    public List<string> Items { get; set; }
}

Here's another way using XDocument

void Main()
{
    var doc = XDocument.Parse("<Items><Item>a</Item><Item>b</Item></Items>");

    var list = doc.Element("Items").Elements("Item").Select (d => (string)d);

    list.Dump();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.