我拥有的XML文档格式如下:
<response>
<forecast>
<txt_forecast>
<forecastdays>
<forecastday>
<period>0</period>
<fctext>Sunny</fctext>
</forecastday>
<forecastday>
<period>1</period>
<fctext>Cloudy></fctext>
</forecastday>
</forecastdays>
</txt_forecast>
</forecast>
</response>我目前掌握的代码是:
public String getcurrentForecast()
{
XmlDocument doc = new XmlDocument();
doc.Load("http://api.wunderground.com/api/74e1025b64f874f6/forecast/conditions/q/zmw:00000.1.95784.xml");
XmlNode node = doc.DocumentElement.SelectSingleNode("/response/forecast/txt_forecast/forecastdays/forecastday");我对XML阅读很陌生,我花了两天的时间试图理解各种来源的示例。我想使用'XMLDocument‘属性作为我的代码。
如何选择“perid0”节点并获得"fctext“文本?
发布于 2013-12-01 23:24:39
如下所示:
XmlDocument doc = new XmlDocument();
doc.Load("http://api.wunderground.com/api/74e1025b64f874f6/forecast/conditions/q/zmw:00000.1.95784.xml");
XmlNode node = doc.DocumentElement.SelectSingleNode("/response/forecast/txt_forecast/forecastdays/forecastday[period=0]/fcttext");
String Forecast = node.InnerText;更新:这里有一个免费的实用程序,可以帮助您快速找到正确的XPath表达式:http://www.bubasoft.net/product/xpath-builder/
发布于 2013-12-01 23:24:09
您的XPath查询应该类似于
//forecastday/period[text()='0']/../fcttext发布于 2013-12-01 23:12:38
不如使用不同的库,XDocument,而不是:
byte[] data;
using (WebClient webClient = new WebClient())
data = webClient.DownloadData(urlToDocument);
string str = Encoding.Default.GetString(data);
var doc = XDocument.Load(str);
var node = doc.Descendants("period")
.Where(elem => elem.Value == "0")
.First().NextNode;
var fcText = ((XElement)node).Value;https://stackoverflow.com/questions/20318424
复制相似问题