如何檢查xml文件以確定是否存在某些元素?比如我有從XML:c#在xml中檢查元素
http://www.google.com/ig/api?weather=vilnius&hl=eng
我要檢查,如果 「wind_condition」 存在的話:
if ("wind_condition") {do something}
如何檢查xml文件以確定是否存在某些元素?比如我有從XML:c#在xml中檢查元素
http://www.google.com/ig/api?weather=vilnius&hl=eng
我要檢查,如果 「wind_condition」 存在的話:
if ("wind_condition") {do something}
這將確定該文件包含單詞wind_condition
。
if(xml.ToString().Contains("wind_condition"))
{
// do something
}
如果你想要的元素wind_condition
if(xml.Descendants("wind_condition").Count() > 0)
{
// do something
}
嘗試:
的XmlNodeList列表= xml.SelectNodes( 「// wind_condition」);
然後,只需檢查返回的列表並相應地進行處理。
+1:經過測試和工作。 – zimdanen
您可以使用這樣的查詢文件,使用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();
示例XML在'current_conditions'中具有'wind_condition',而不是'forecast_information'。 – zimdanen
@zimdanen好抓。更新我的答案,使用** Elements()**選擇* weather *的所有孩子。 – McGarnagle
由於您的根節點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
{
}
+1:已測試並正常工作 – zimdanen
我不得不編輯,試圖找出被問到的是什麼。希望我明白了。 – Robaticus
google for xpath c# –
閱讀關於讀取xml中的子節點。 http://www.kirupa.com/forum/showthread.php?292473-Reading-Child-nodes-from-XML-file-C – Brian