2013-10-12 55 views
0

從以下GeoCodeRespose xml中,我們如何在c#程序中使用xpath提取地點,路線和街道號的值。如何使用xpaths在c#中提取xml節點

<GeocodeResponse> 
<status>OK</status> 
<result> 
<type>street_address</type> 
<formatted_address>1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA</formatted_address> 
<address_component> 
<long_name>1600</long_name> 
<short_name>1600</short_name> 
<type>street_number</type> 
</address_component> 
<address_component> 
<long_name>Amphitheatre Pkwy</long_name> 
<short_name>Amphitheatre Pkwy</short_name> 
<type>route</type> 
</address_component> 
<address_component> 
<long_name>Mountain View</long_name> 
<short_name>Mountain View</short_name> 
<type>locality</type> 
<type>political</type> 
</address_component> 
</result> 
</GeocodeResponse> 

到目前爲止,我可以得到的XML文檔中的XML,並能得到格式的地址的值,如下

XmlDocument doc=GetGeoCodeXMLResponse(); 
    XPathDocument document = new XPathDocument(new XmlNodeReader(doc)); 
    XPathNavigator navigator = document.CreateNavigator(); 

    XPathNodeIterator resultIterator = navigator.Select("/GeocodeResponse/result"); 
     while (resultIterator.MoveNext()) 
     { 

      XPathNodeIterator formattedAddressIterator = resultIterator.Current.Select("formatted_address"); 
      while (formattedAddressIterator.MoveNext()) 
      { 
       string FullAddress = formattedAddressIterator.Current.Value; 

      } 
     } 
+0

任何你不想使用XmlSerializer或LinqtoXml的原因? –

+0

我打開使用XmlSerializer或LinqtoXml,如果你能給我一個例子來從xml中提取這些類型的值 – rumi

+0

這個XML是否每次需要反序列化時都一致? –

回答

0

您可以使用LinqToXml,試試這個,你會得到一個匿名類型與所有你需要的屬性。

var xDoc = XDocument.Parse(xmlString); 

var result = xDoc.Descendants("result").Select(c => 
       new 
       { 
       FormattedAddress = c.Element("formatted_address").Value, 
       StreetNumber = c.Descendants("address_component") 
         .First(e => e.Element("type").Value == "street_number").Element("short_name").Value, 
       Route = c.Descendants("address_component") 
         .First(e => e.Element("type").Value == "route").Element("short_name").Value, 
       Locality = c.Descendants("address_component") 
         .First(e => e.Element("type").Value == "locality").Element("short_name").Value 
      }).First(); 
1

如果你的XML是一致的,這可能是最簡單的方法。

創建表示XML對象:

public GeocodeResponse 
{ 
    public string Status { get; set; } 
    public Result Result { get; set; } 

    public class Result 
    { 
    public string type { get; set; } 
    public string formatted_address { get; set; } 
    // etc.. 
    } 
} 

反序列化在XML對象。

var serializer = new XmlSerializer(typeof(GeocodeResponse)); 
GeocodeResponse geocodeReponse = 
    (GeocodeResponse)serializer.Deserialize(xmlAsString);