2015-09-22 15 views
0

任何selectSingleNode方法,我想从一个XML文件属性:XmlNodeList中不具有通用的Windows应用程序或XAML

<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; 

但是,当我尝试这样做,通用的Windows应用程序(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(); 
} 

回答

1

你可以使用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"; 

找到的第一个后代所谓的命名空间+位置

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

然后拿到属性城市的价值:

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

谢谢... ...工作有啥与UWP回事呢?为什么不支持所有的类和它们的方法? – envyM6

相关问题