我使用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输入中某个元素的值是否存在,并且不为null。
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>
答案 0 :(得分:0)
我认为扩展方法是处理此问题的好方法。它需要一些检查,因为有很多时候值可能为null,但这应该涵盖你的用例。
void Main()
{
var doc = XDocument.Load(@"C:\Test\test.xml");
var city = doc.Descendants("address_component").FirstOrDefault(e => e.Element("type") != null
&& e.Element("type").Value =="locality");
if(city != null){
Console.WriteLine (city.GetElementIfExists("short_name"));
} else {
Console.WriteLine ("No short name found");
}
}
public static class Extensions {
public static string GetElementIfExists(this XElement @this, string element){
return @this.Element(element) != null ? @this.Element(element).Value : String.Empty;
}
}