我正在使用 linq to xml 使用下面的代码从 xml 输入中读取值
var values = xDoc.Descendants("result").Select(c =>
new
{
FullAddress = c.Element("formatted_address").Value,
CountryName = c.Descendants("address_component")
.First(e => e.Element("type").Value == "country").Element("long_name").Value,
CountryNameCode = c.Descendants("address_component")
.First(e => e.Element("type").Value == "country").Element("short_name").Value,
CityName = c.Descendants("address_component")
.First(e => e.Element("type").Value == "locality").Element("short_name").Value,
}).First();
我们如何检查xml输入中某个元素的值是否存在并且不为空,例如
CityName = c.Descendants("address_component").First(e => e.Element("type").Value =="locality").Element("short_name").Value
我的输入 xml 是
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
<status>OK</status>
<result>
<type>postal_code</type>
<formatted_address>Inverclyde PA16 0XN, UK</formatted_address>
<address_component>
<long_name>PA16 0XN</long_name>
<short_name>PA16 0XN</short_name>
<type>postal_code</type>
</address_component>
<address_component>
<long_name>Inverclyde</long_name>
<short_name>Inverclyde</short_name>
<type>administrative_area_level_2</type>
<type>political</type>
</address_component>
<address_component>
<long_name>United Kingdom</long_name>
<short_name>GB</short_name>
<type>country</type>
<type>political</type>
</address_component>
<geometry>
<location>
<lat>55.9437962</lat>
<lng>-4.8097700</lng>
</location>
<location_type>APPROXIMATE</location_type>
<viewport>
<southwest>
<lat>55.9426062</lat>
<lng>-4.8127289</lng>
</southwest>
<northeast>
<lat>55.9453041</lat>
<lng>-4.8075776</lng>
</northeast>
</viewport>
<bounds>
<southwest>
<lat>55.9428874</lat>
<lng>-4.8127289</lng>
</southwest>
<northeast>
<lat>55.9450229</lat>
<lng>-4.8075776</lng>
</northeast>
</bounds>
</geometry>
</result>
</GeocodeResponse>