C# 从XML c读取特定位置#

C# 从XML c读取特定位置#,c#,xml,imdb,C#,Xml,Imdb,我有一个XML文件,它从imdb获取信息,就像这样 <?xml version="1.0" encoding="UTF-8"?> <root response="True"> <movie title="Game of Thrones" year="2011–" rated="TV-MA" released="17 Apr 201

我有一个XML文件,它从imdb获取信息,就像这样

<?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>
但这确实给了我一个错误

XDocument doc = XDocument.Parse("game of thrones.xml");
我也试过了,但也没用

var xml = new XmlDocument();
xml.LoadXml("game of thrones.xml");
string dummy = xml.DocumentElement.SelectSingleNode("imdbRating").InnerText;
Console.WriteLine(dummy);
Console.ReadLine();
第二个给出了这行中的一个错误

xml.LoadXml("game of thrones.xml");
错误是


System.Xml.dll中发生类型为“System.Xml.XmlException”的未处理异常

其他信息:根级别的数据无效。第1行,位置1


XDocument.Parse
XmlDocument.LoadXml
都希望它们的参数是包含xml的字符串,而不是包含文件名的字符串。您想使用
XmlDocument.Load
,它接受一个文件名:

XmlDocument xml = new XmlDocument();
xml.Load("game of thrones.xml");

您选择的
电影
节点不正确

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;
您需要选择的节点是
电影
,而不是
电影标题


但是,它不应该在
XDocument.Parse
处抛出错误。再次检查您的
XML
,我尝试了使用您的示例
XML
,效果很好。确保文件开头没有空格。

请包括您看到的确切错误抱歉,我忘了,我添加了它。System.Xml.dll中出现了一个未经处理的“System.Xml.XmlException”类型的异常。其他信息:名称中不能包含“”字符(十六进制值0x20)。当我使用XDocument.loadXdocument时,它会给我这个错误。显然,XDocument不喜欢文件名中的空格。我将编辑答案以使用XmlDocument
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;