我的XML文档包含国家,城市和其他地理对象列表,如下所示:
<mondial>
<continent id="1" name="Europe"/>
<continent id="2" name="Asia"/>
<continent id="3" name="America"/>
<continent id="4" name="Australia/Oceania"/>
<continent id="5" name="Africa"/>
<country id="f0_136" name="Albania" capital="f0_1461" population="3249136" datacode="AL" total_area="28750" population_growth="1.34" infant_mortality="49.2" gdp_agri="55" gdp_total="4100" inflation="16" indep_date="28 11 1912" government="emerging democracy" car_code="AL">
<name>
Albania
</name>
<city id="f0_1461" country="f0_136" longitude="10.7" latitude="46.2">
<name>
Tirane
</name>
<population year="87">
192000
</population>
</city>
<city id="f0_36498" country="f0_136" longitude="19.2" latitude="42.2">
<name>
Shkoder
</name>
<population year="87">
62000
</population>
<located_at type="lake" water="f0_39058"/>
</city>
<city id="f0_36504" country="f0_136" longitude="19.3" latitude="41.2">
<name>
Durres
</name>
<population year="87">
60000
</population>
<located_at type="sea" water="f0_38042"/>
</city>
//etc it's only small part
并使用LINQtoXML显示人口超过100000的所有城市的任务
有些城市根本没有population
。
所以我做到了:
var cities = from c in doc.Descendants("city")
where c.Element("population") != null
&& (int)c.Element("population") > 100000
select new
{
name = c.Element("name"),
population = c.Element("population")
};
foreach (var c in cities)
Console.WriteLine("{0}{1}", c.name, c.population);
但它只显示了大约一半的城市