【问题标题】:Read specific place from XML c#从 XML c# 读取特定位置
【发布时间】:2016-02-28 18:45:57
【问题描述】:

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

错误是

System.Xml.dll 中出现“System.Xml.XmlException”类型的未处理异常

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

【问题讨论】:

  • 请包括您看到的确切错误
  • 抱歉我忘记了,我加了

标签: c# xml imdb


【解决方案1】:

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

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

【讨论】:

  • System.Xml.dll 中发生了“System.Xml.XmlException”类型的未处理异常附加信息:“”字符,十六进制值 0x20,不能包含在名称中。当我使用 XDocument.Load 时,它给了我这个错误
  • 显然 XDocument 不喜欢文件名中的空格。我将编辑答案以使用 XmlDocument
【解决方案2】:

您错误地选择了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;

你需要选择的节点是movie,而不是movie title!

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2021-03-30
    相关资源
    最近更新 更多