使用 XElement 将此 XML 解析为数组

Using XElement to parse this XML into an array

假设我有一个人 class:

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

如何解析包含

的 XML 文件
<person>
    <name>a</name>
</person>
<person>
    <name>b</name>
</person>

成两个 Person 的数组?

这是这个问题的变体:Specific parsing XML into an array

唯一不同的是,整个XML周围没有<people></people><person> 立即开始。

试试这个

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; }
    }
}