LINQ to XML解析单个对象

时间:2018-01-29 23:34:35

标签: c# linq linq-to-xml

我正在尝试解析这样的XML文档:

<root>
    <first>1</first>
    <second>2</second>
</root>

要像这样结构:

class SomeClass
{
    ...

    public string First;
    public string Second;
}

但据我所知,我只能在select语句中创建新对象,它只能应用于集合,而根元素不是集合。

当然,我可以单独选择字段,如:

new SomeClass(doc.Element("first").Value, doc.Element("second").Value);

但我真的很感兴趣,是否可以在一个 LINQ语句中执行此操作(仅使用doc变量一次并在LINQ语句中创建对象)?

换句话说:是否可以创建不在Select()方法中的对象?

1 个答案:

答案 0 :(得分:1)

根元素可能不是集合,但是当您解析xml时,您的doc变量 元素的集合,包括根元素。所以你仍然可以使用Select:

string xml = @"<root><first>1</first><second>2</second></root>";

var doc = XDocument.Parse(xml);
var collectionOfSomeClass = doc.Elements()
                            .Select(x => new SomeClass 
                                        { First = x.Element("first").Value, 
                                          Second = x.Element("second").Value 
                                        });