2

假设我有一个 XML 文件:

<locations>
    <country name="Australia">
        <city>Brisbane</city>
        <city>Melbourne</city>
        <city>Sydney</city>
    </country>
    <country name="England">
        <city>Bristol</city>
        <city>London</city>
    </country>
    <country name="America">
        <city>New York</city>
        <city>Washington</city>
    </country>
</locations>

我希望它变平(这应该是最终结果):

Australia
Brisbane
Melbourne
Sydney
England
Bristol
London
America
New York
Washington

我试过这个:

var query = XDocument.Load(@"test.xml").Descendants("country")
    .Select(s => new
    {
        Country = (string)s.Attribute("name"),
        Cities = s.Elements("city")
            .Select (x => new { City = (string)x })
    });

但这会返回一个嵌套列表query。像这样:

{ Australia, Cities { Brisbane, Melbourne, Sydney }},
{ England, Cities { Bristol, London }},
{ America, Cities { New York, Washington }}

谢谢

4

2 回答 2

5

SelectMany应该在这里解决问题。

var result = 
    XDocument.Load(@"test.xml")
    .Descendants("country")
    .SelectMany(e => 
        (new [] { (string)e.Attribute("name")})
        .Concat(
            e.Elements("city")
            .Select(c => c.Value)
        )
    )
    .ToList();
于 2012-08-29T01:50:11.507 回答
4

这是一种使用查询语法的方法:

var query = from country in XDocument.Load(@"test.xml").Descendants("country")
            let countryName = new [] {(string)country.Attribute("name")}
            let cities = country.Elements("city").Select(x => (string)x)
            from place in countryName.Concat(cities)
            select place;
于 2012-08-29T02:02:05.550 回答