【发布时间】:2009-12-23 10:38:26
【问题描述】:
我意识到这是一个转贴,但我需要,因为我不能使用 LINQ,(在我之前的帖子中要求)。
我需要从下面的 XML 文档中读取 woeid。我需要读取数据并将其存储到字符串变量中,以便查询 yahoo 天气服务。
查询返回的XML:
<query yahoo:count="1"
yahoo:created="2009-12-22T08:30:31Z"
yahoo:lang="en-US"
yahoo:updated="2009-12-22T08:30:31Z"
yahoo:uri="http://query.yahooapis.com/v1/yql?q=select+woeid+from+geo.places+where+text%3D%22farnborough%2C+greater+london%2Cuk%22">
<diagnostics>
<publiclyCallable>true</publiclyCallable>
<url execution-time="32">
http://where.yahooapis.com/v1/places.q(farnborough%2C%20greater%20london%2Cuk);start=0;count=10
</url>
<user-time>33</user-time>
<service-time>32</service-time>
<build-version>4265</build-version>
</diagnostics>
<results>
<place>
<woeid>19941</woeid>
</place>
</results>
</query>
有人可以建议我如何通过 XPath 或与 .net 2.0 中的库兼容的其他方式来做到这一点吗?
感谢您的回答。因此,我使用下面的方法,但是在加载 XML 文档时抛出异常:
private string getWOEID(string UserLocation, string UserCountry)
{
string woeID = "";
if (UserLocation == "farnborough") { UserLocation = "farnborough" + "%2C" + "hampshire"; }
String reqUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20woeid%20from%20geo.places%20where%20text%3D%22" + UserLocation + "%2C" + UserCountry + "%22&format=xml";
XmlDocument doc = new XmlDocument();
doc.LoadXml(reqUrl);
string woeid = doc.SelectSingleNode("query/results/place/woeid/text()").Value;
return woeID;
}
【问题讨论】:
-
查看我的更新答案。
-
感谢 ChaosPandion 我用修复重建。但是还是在doc.LoadXml(reqUrl)语句中抛出异常:{"根级别的数据无效。第1行,位置1。"}
-
我更新了我的答案以满足您的需求。我将 LoadXml 切换为 Load。
-
感谢混沌。它的工作几乎除了一个空值使用返回: string woeid = doc.SelectSingleNode("query/results/place/woeid/text()").Value;我也试过: string woeid = doc.SelectSingleNode("query/results/place/woeid/text()").InnerText;但不是快乐!
-
我最终使用了 Mark 的方式 string woeId = doc.GetElementsByTagName("woeid")[0].InnerText;这对我有用。
标签: c# .net xml xpath .net-2.0