2012-05-07 51 views
0

如何檢查xml文件以確定是否存在某些元素?比如我有從XML:c#在xml中檢查元素

http://www.google.com/ig/api?weather=vilnius&hl=eng

我要檢查,如果 「wind_condition」 存在的話:

if ("wind_condition") {do something}

+0

我不得不編輯,試圖找出被問到的是什麼。希望我明白了。 – Robaticus

+0

google for xpath c# –

+0

閱讀關於讀取xml中的子節點。 http://www.kirupa.com/forum/showthread.php?292473-Reading-Child-nodes-from-XML-file-C – Brian

回答

2

這將確定該文件包含單詞wind_condition

if(xml.ToString().Contains("wind_condition")) 
{ 
    // do something 
} 

如果你想要的元素wind_condition

if(xml.Descendants("wind_condition").Count() > 0) 
{ 
    // do something 
} 
+0

OP正在尋找一個元素,而不是一個字符串。 – zimdanen

+0

每個問題('我如何檢查一個xml文件以確定是否存在某些元素?')和註釋('查找元素wind_condition'),他想要一個元素。 – zimdanen

+0

萬一你是對的,我增加了更多的答案。 –

4

嘗試:

的XmlNodeList列表= xml.SelectNodes( 「// wind_condition」);

然後,只需檢查返回的列表並相應地進行處理。

+0

+1:經過測試和工作。 – zimdanen

2

您可以使用這樣的查詢文件,使用LINQ到XML(未經測試):

XDocument xdoc = XDocument.Load("http://www.google.com/ig/api?weather=vilnius&hl=eng"); 
XElement[] myElements = xdoc.Root.Element("weather") 
    .Elements() 
    .Where(xelement => xelement.Element("wind_condition") != null) 
    .ToArray(); 
+0

示例XML在'current_conditions'中具有'wind_condition',而不是'forecast_information'。 – zimdanen

+1

@zimdanen好抓。更新我的答案,使用** Elements()**選擇* weather *的所有孩子。 – McGarnagle

2

由於您的根節點xml_api_reply,以下應返回你一個bool是否wind_condition存在與否(我只是測試它,它似乎是工作)

var result = (from t in loadedData.Descendants("xml_api_reply") 
        select t.Descendants("wind_condition").Any()).Single(); 

if(result) // equals to if wind_condition exists 
{ 
} 
+0

+1:已測試並正常工作 – zimdanen