从 XML c# 中读取特定位置

Read specific place from XML c#

所以我有一个 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>

我想得到一个特定的属性,它是 imdbRating 我从这个网站看了很多解析问题,但我仍然想不出我想出的最佳解决方案是,

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

但这行确实给我一个错误

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

错误是

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.

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

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

您 select 错误地 movie 节点。

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;

你需要select的节点是movie,不是movie title!

但是,它不应该在 XDocument.Parse 处抛出错误。再次检查您的 XML,我尝试了您的样本 XML,它工作得很好。确保文件开头没有空 space。