Reputation: 309
I'm having some trouble parsing through an XML document to get the data that I want. I have this xml document:
<root response="True">
<movie title="Spider-Man 2" year="2004" rated="PG-13" runtime="127 min"
genre="Action, Adventure" director="Sam Raimi"
actors="Tobey Maguire, Kirsten Dunst, James Franco, Alfred Molina"
metascore="83" type="movie" />
</root>
I'm having some trouble, since I want to save those attributes and I'm not really sure how. I've tried using the XmlElement
class and the SelectSingeNode
method, but I can't seem to get it to work. What ive tried so far is:
root.SelectSingleNode(@"\\movie[title]).InnerText;
but I keep getting the following error:
System.Xml.XPath.XPathException'\\\\movie[@genre]' has an invalid token.
I'd like to be able to save, for example, the title of the movie. What can I do differently?
Upvotes: 0
Views: 44
Reputation: 3653
This is only a for example and I suggest you make a class instead, but this should work for you:
foreach (XmlElement movie in root.SelectNodes("//movie"))
{
string title = string.Empty;
string year = string.Empty;
//etc
title = movie.Attributes["title"] != null ? movie.Attributes["title"].Value : string.Empty;
//etc
}
Upvotes: 1
Reputation: 874
Try this to get the value of a desired attribute e.g. title:
root.SelectSingleNode("/root/movie/@title").Value
Upvotes: 1