问题
Ok so I am trying to learn how to work with XAML and how to build new windows metro applications using Visual Studio 11 Developer Preview.
I have a problem though I don't know how to read XML files the same way I use to using C#. For example here is how I did it in the past.
private void Button_Click(object sender, RoutedEventArgs e)
{
string UrlString = "http://v1.sidebuy.com/api/get/73d296a50d3b824ca08a8b27168f3b85/?city=nashville&format=xml";
XmlTextReader reader = new XmlTextReader(UrlString);
XmlNodeType type;
while (reader.Read())
{
type = reader.NodeType;
if ((type == XmlNodeType.Element) && (reader.Name == "highlights"))
{
reader.Read();
if (reader.Value != "" && reader.Value != null)
{
listBox1.Items.Add(reader.Value);
}
}
}
}
But this won't work in my metro application. I need to know how to do this for metro. Apparently XmlTextReader is no longer valid. Any code or suggestions?
Thanks
回答1:
You can use XmlDocument.LoadFromUriAsync. This should also make your code a lot simpler.
private async void Button_Click(object sender, RoutedEventArgs e)
{
string UrlString = "http://v1.sidebuy.com/api/get/73d296a50d3b824ca08a8b27168f3b85/?city=nashville&format=xml";
var xmlDocument = await XmlDocument.LoadFromUriAsync(UrlString);
//read from xmlDocument for your values.
}
EDIT: Fixed code based on comment.
回答2:
you need to add the async/await keyworks to the method
private async void Button_Click(object sender, RoutedEventArgs e)
var xmlDocument = await XmlDocument.LoadFromUriAsync(UrlString);
回答3:
You can also XmlSerializer class which allows you to declare the object types used in your xml and maps directly to them. The Deserialize and Serialize methods work with any stream and greatly simplify using xml data.
var xmlserializer = new XmlSerializer(typeof(yourcollectionclass), new []{typeof(yourchildclass1),typeof(yourchildclass2)});
var xml = (yourcollectionclass) xml.deserialize(stream)
来源:https://stackoverflow.com/questions/9477158/metro-application-how-to-read-xml-api