gpt4 book ai didi

c# - 如何在 C# WPF 应用程序中解析 Xml

转载 作者:太空宇宙 更新时间:2023-11-03 21:16:53 25 4
gpt4 key购买 nike

UTF 似乎不适用于我的代码。它在第 125 行说错误。

<feed>

</feed>

我已经尝试指定正在使用的 utf 但似乎不起作用

  var results = XElement.Load("games.xml")
.Element("content.items")
.Element("content.head")
.Element("content.body")
.Elements("results")
.Elements("result");

var query = (from result in results
let homeTeam = result.Element("home-team")
let awayTeam = result.Element("away-team")
let lastScorer = result.Descendants("scorers").Elements("scorer").OrderByDescending(p => (int)p.Attribute("time")).FirstOrDefault()
select new
{
HomeTeam = homeTeam.Element("team-name").Value,
AwayTeam = awayTeam.Element("team-name").Value,

HomeTeamScore = homeTeam.Element("score").Value,
AwayTeamScore = awayTeam.Element("score").Value,

LastScorerName = lastScorer != null ? lastScorer.Element("player-name").Value : string.Empty,
LastScoreTime = lastScorer != null ? (int?)lastScorer.Attribute("time") : null
}).ToList();

最佳答案

使用 Linq To XML 让您的生活更轻松.

下面的代码可以正常工作,并且比使用低级 XmlReader 更具可读性。

假设 xml 存储在名为 games.xml 的文件中。

    var results = XElement.Load("games.xml")
.Element("content.items")
.Element("content.head")
.Element("content.body")
.Elements("results")
.Elements("result");

var query = (from result in results
let homeTeam = result.Element("home-team")
let awayTeam = result.Element("away-team")
let lastScorer = result.Descendants("scorers").Elements("scorer").OrderByDescending(p => (int)p.Attribute("time")).FirstOrDefault()
select new
{
HomeTeam = homeTeam.Element("team-name").Value,
AwayTeam = awayTeam.Element("team-name").Value,

HomeTeamScore = homeTeam.Element("score").Value,
AwayTeamScore = awayTeam.Element("score").Value,

LastScorerName = lastScorer != null ? lastScorer.Element("player-name").Value : string.Empty,
LastScoreTime = lastScorer != null ? (int?)lastScorer.Attribute("time") : null
}).ToList();

关于c# - 如何在 C# WPF 应用程序中解析 Xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33596791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com