0

Let's say I have a Person class:

public class Person
{
    public string Name { get; set; }
}

How do I parse an XML file containing

<person>
    <name>a</name>
</person>
<person>
    <name>b</name>
</person>

into an array of two Persons?

This is a variant of this question: Specific parsing XML into an array

The only difference is that there is no <people></people> surrounding the whole XML. The <person>s start immediately.

Community
  • 1
  • 1
code-ninja-54321
  • 509
  • 4
  • 12
  • 6
    If there is no outer root tag, then it is invalid xml by definition. You'd have to parse it yourself, or modify the string to make it valid. – Jonesopolis Nov 07 '16 at 21:20
  • If there is no outer root tag then it is an invalid xml like @Jonesopolis said – Maddy Nov 07 '16 at 21:33
  • This "XML" is invalid, see https://www.w3.org/TR/REC-xml/#dt-root. But if you need to load it into an XDocument anyway, see [C# XDocument Load with multiple roots](https://stackoverflow.com/questions/18186225/c-sharp-xdocument-load-with-multiple-roots). Or do you really need to deserialize to `List` and not load into an `XElement`? – dbc Nov 07 '16 at 23:10

1 Answers1

2

Try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = 
                "<person>" +
                    "<name>a</name>" +
                "</person>" +
                "<person>" +
                    "<name>b</name>" +
                "</person>";
            xml = "<Root>" + xml + "</Root>";

            XDocument doc = XDocument.Parse(xml);

            List<Person> people = doc.Descendants("person").Select(x => new Person() {
                Name = (string)x.Element("name")
            }).ToList();
        }
    }
    public class Person
    {
        public string Name { get; set; }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20