2011-03-21 60 views
0

我想從下面的XML字符串返回緯度節點(例如)一個XML元素返回只/單字符串值(來自雅虎地理編碼API。)我想從使用LINQ

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

我已經將此XML成功加載到XElement實例中,但似乎無法找到將緯度節點(例如)加載到字符串變量中的方式。如果沒有節點或節點是空的,那麼我想得到一個空或空字符串。如果有多個(不會有,但只是爲了以防萬一)然後返回第一個實例。

我想這將是容易的,但我不能得到它的工作。我試過的所有Linq查詢都返回null。

雖然我在這,如果你能有足夠的詳細解釋一下,這樣我還可以得到錯誤節點。我只提到它,因爲它處於不同的級別。

謝謝。

賽斯

回答

3

爲了得到緯度值:

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

而且你可以用下面得到的錯誤元素:

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

我使用resultXML作爲參考解析的XML。

+0

這做到了完全一樣。謝謝。 – 2011-03-23 22:37:22

1

確保您使用的System.Xml.XPath命名空間,並嘗試:

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

el應包含XElement類或null如果沒有找到該節點。

MSDN docsXPath 1.0關於如何使用它的詳細信息。