XmlNodeList 在 Universal Windows App 或 XAML 中没有任何 SelectSingleNode 方法

XmlNodeList doesn't have any SelectSingleNode method in Universal Windows App or XAML

我正在尝试从 XML 文件中获取属性:

<yweather:location city="London" region="" country="United Kingdom"/>
<yweather:units temperature="C" distance="km" pressure="mb" speed="km/h"/>
<yweather:wind chill="13" direction="280" speed="19.31"/>
<yweather:atmosphere humidity="77" visibility="9.99" pressure="982.05" rising="0"/>
<yweather:astronomy sunrise="6:44 am" sunset="6:58 pm"/>

在我的 Winforms 应用程序中,我可以通过以下方式轻松做到这一点(假设我正在检索 city 的值):

string query = String.Format("url");

XmlDocument wData = new XmlDocument();
wData.Load(query);

XmlNamespaceManager man = new XmlNamespaceManager(wData.NameTable);
man.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");

XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");

string city = channel.SelectSingleNode("yweather:location", man).Attributes["city"].Value;

但是当我尝试为 Universal Windows App(XAML) 执行此操作时,至少根据智能感知,没有名为 SelectSingleNode 的方法。我该怎么做?此外,似乎并不是所有来自 C#/.NET 框架的 类 都可以在 UWP/XAML 中访问,所以这是怎么回事?

这是我试过的:

private async void SomeThing()
{
    string url = String.Format("url");

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); 
    StreamReader reader = new StreamReader(response.GetResponseStream());

    XmlDocument wData = new XmlDocument();
    wData.Load(reader);

    XmlNamespaceManager man = new XmlNamespaceManager(wData.NameTable);
    man.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");

    string city = wData.SelectSingleNode("city").toString();
}

你可以使用 XDocument.

首先,得到 XML:

Uri uri = new Uri("http://weather.yahooapis.com/forecastrss?p=USCA1116");
HttpClient client = new HttpClient();
var response = await client.GetStringAsync(uri);

然后根据 XML 响应创建 XDocument 对象:

XDocument xdoc = XDocument.Parse(response);

声明命名空间对象:

XNamespace yWeather = "http://xml.weather.yahoo.com/ns/rss/1.0";

找到名为 namespace+location 的第一个后代:

var locationNode = xdoc.Descendants(yWeather + "location").FirstOrDefault();

然后获取属性值city:

var city = locationNode.Attribute("city").Value.ToString();