首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XMLDocument选择

XMLDocument选择
EN

Stack Overflow用户
提问于 2013-12-01 23:09:13
回答 3查看 194关注 0票数 2

我拥有的XML文档格式如下:

代码语言:javascript
复制
<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>

我目前掌握的代码是:

代码语言:javascript
复制
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“文本?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-12-01 23:24:39

如下所示:

代码语言:javascript
复制
    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/

票数 2
EN

Stack Overflow用户

发布于 2013-12-01 23:24:09

您的XPath查询应该类似于

代码语言:javascript
复制
//forecastday/period[text()='0']/../fcttext
票数 2
EN

Stack Overflow用户

发布于 2013-12-01 23:12:38

不如使用不同的库,XDocument,而不是:

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20318424

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档