如何使用LinqtoXml提取xml节点

时间:2013-10-13 18:07:27

标签: c# linq linq-to-xml

使用下面的XML我们如何使用linq提取lat和lng的值到xml lambda查询

<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
<status>OK</status>
<result>
    <type>premise</type>
    <formatted_address>Livingston, West Lothian EH54, UK</formatted_address>
    <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.8831307</lat>
            <lng>-3.5162945</lng>
        </location>
        <location_type>APPROXIMATE</location_type>
    </geometry>
    <partial_match>true</partial_match>
</result>

我使用这样的东西来提取其他节点

  var xDoc = XDocument.Parse(doc.OuterXml);

        model = 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,
                      }).First();

1 个答案:

答案 0 :(得分:2)

XDocument doc=XDocument.Load(url);
var location=doc.Descendants("location")
                .Select(x=>
                    new
                    {
                          lat=x.Element("lat").Value,
                          lng=x.Element("lng").Value
                    }).First();

location.lat;
location.lng;