如何使用xpaths在c#中提取xml节点

时间:2013-10-12 23:08:47

标签: c# xml xpath

从以下GeoCodeRespose xml中,我们如何在c#程序中使用xpath提取地点,路线和街道号码的值。

<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;

            }
        }

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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();