Search code examples
c#xmlimdb

Read specific place from XML c#


So I have an XML file and it gets information from imdb which is like that,

<?xml version="1.0" encoding="UTF-8"?>
<root response="True">
    <movie title="Game of Thrones" year="2011–" rated="TV-MA" released="17 Apr 2011" runtime="56 min" genre="Adventure, Drama, Fantasy" director="N/A" writer="David Benioff, D.B. Weiss" actors="Peter Dinklage, Lena Headey, Emilia Clarke, Kit Harington" plot="Several noble families fight for control of the mythical land of Westeros." language="English" country="USA" awards="Won 1 Golden Globe. Another 133 wins &amp; 248 nominations." poster="http://ia.media-imdb.com/images/M/MV5BNTgxOTI4NzY2M15BMl5BanBnXkFtZTgwMjY3MTM2NDE@._V1_SX300.jpg" metascore="N/A" imdbRating="9.5" imdbVotes="868,876" imdbID="tt0944947" type="series"/>
</root>

I wanna get a specific attribute which is imdbRating I've looked so many parse questions from this site and I still couldn't figured it out best solution I come up with is,

XDocument doc = XDocument.Parse("game of thrones.xml");
string var = doc.Descendants("movie title").Attributes("imdbRating").FirstOrDefault().Value;
labelImdb.Content = var;

but it does give me an error in this line

XDocument doc = XDocument.Parse("game of thrones.xml");

I also tried that and didn't work either

var xml = new XmlDocument();
xml.LoadXml("game of thrones.xml");
string dummy = xml.DocumentElement.SelectSingleNode("imdbRating").InnerText;
Console.WriteLine(dummy);
Console.ReadLine();

second one gives an error in this line,

xml.LoadXml("game of thrones.xml");

error is

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

Additional information: Data at the root level is invalid. Line 1, position 1.


Solution

  • You are selecting the movie node incorrectly.

    var xmlString = File.ReadAllText(@"C:\YourDirectory\YourFile.xml"); //or from service
    
    var xDoc = XDocument.Parse(xmlString);
    var rating = xDoc.Descendants("movie").First().Attribute("imdbRating").Value;
    

    The node you need to select is movie, not movie title!

    But, it should not throw error at XDocument.Parse. Check your XML once again, I tried with your sample XML and it worked just fine. Make sure there's no empty space at beginning of file.