开发者

I want to return the only/single string value from an XML Element using Linq

I want to return t开发者_如何学编程he latitude node (for example) from the following XML string (from Yahoo geocoding API.)

<ResultSet version="1.0">
  <Error>0</Error>
  <ErrorMessage>No error</ErrorMessage>
  <Locale>us_US</Locale>
  <Quality>60</Quality>
  <Found>1</Found>
  <Result>
    <quality>87</quality>
    <latitude>37.68746446</latitude>
    <longitude>-79.6469878</longitude>
    <offsetlat>30.895931</offsetlat>
    <offsetlon>-80.281192</offsetlon>
    <radius>500</radius>
    <name></name>
    <line1>123 Main Street</line1>
    <line2>Greenville, SC  29687</line2>
    <line3></line3>
    <line4>United States</line4>
    <house>123</house>
    <street>Main Street</street>
    <xstreet></xstreet>
    <unittype></unittype>
    <unit></unit>
    <postal>29687</postal>
    <neighborhood></neighborhood>
    <city>Greenville</city>
    <county>Greenville County</county>
    <state>South Carolina</state>
    <country>United States</country>
    <countrycode>US</countrycode>
    <statecode>SC</statecode>
    <countycode></countycode>
    <uzip>29687</uzip>
    <hash>asdfsdfas</hash>
    <woeid>127757446454</woeid>
    <woetype>11</woetype>
  </Result>
</ResultSet>

I already have this XML successfully loaded into an XElement instance but I cannot seem to be able to find the way to load the latitude node (for example) into a string variable. If there is no node or the node is empty then I would like to get a Null or Nullstring. If there is more than one (there won't be but just in case) then return the first instance.

I thought this would be easy but I can't get it to work. All of the Linq queries I have tried are returning null.

While I am at it if you could explain it with enough detail so that I can also get the Error node. I only mention it because it is at a different level.

Thanks.

Seth


To get latitude's value:

var latitudeElement = resultXML.Descendants("latitude").FirstOrDefault();
string latitude = latitudeElement == null ? String.Empty : latitudeElement.Value;

And you could get the Error element with the following:

var errorElement = resultXML.Descendants("Error").First();

I'm using resultXML as the reference to the parsed XML.


Make sure you're using the System.Xml.XPath namespace, and try:

var doc = XDocument.Parse(<your xml here>);
var el = doc.XPathSelectElement("ResultSet/Result/latitude");

el should contain an XElement class or null if the node wasn't found.

See the MSDN docs for XPath 1.0 for more info on how to use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜