【问题标题】:c# can't get attributes out of xmlc#无法从xml中获取属性
【发布时间】:2014-05-18 15:36:48
【问题描述】:

我有一个问题,我试图从 url 中获取 xml 文件的属性中的值。

xml:http://thegamesdb.net/api/GetGamesList.php?name=x-men

代码:

public MainPage()
    {
        InitializeComponent();

        var webClient = new WebClient();
        webClient.DownloadStringCompleted += RequestCompleted;
        webClient.DownloadStringAsync(new     Uri("http://thegamesdb.net/api/GetGamesList.php?name=x-men"));
    }

    private void RequestCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            var feedXml = XDocument.Parse(e.Result);

            var gameData = feedXml.Root.Elements("Game").Select(x => new GetGamesList
              {
// ERROR VALUES ARE NULL
                  ID = (int)x.Attribute("id"), 
                  GameTitle = (string)x.Attribute("GameTitle"),
                  ReleaseDate = (string)x.Attribute("ReleaseDate"),
                  Platform = (string)x.Attribute("Platform")
              })
              .ToList();
        }
    }

public class GetGamesList
{
    public int ID { get; set; }
    public string GameTitle { get; set; }
    public string ReleaseDate { get; set; }
    public string Platform { get; set; }
}

希望有人能帮助我,谢谢。

【问题讨论】:

  • 你想只得到一个元素吗?
  • 是的,我现在只是想获得其中一个元素。

标签: c# xml url windows-phone linq-to-xml


【解决方案1】:

id, GameTitle, ReleaseDatePlatform都是Game下的元素,即:

  ID = int.Parse(x.Element("id")), 
  GameTitle = (string)x.Element("GameTitle"),
  ReleaseDate = (string)x.Element("ReleaseDate"),
  Platform = (string)x.Element("Platform")

您还需要解析 int。

【讨论】:

  • 是的,它有效。谢谢。但我认为 是一个“元素”,而 是一个“属性”?,
  • xml 中的属性在元素上,用引号括起来,例如你的代码会像这样解析 xml:<Game id="665" GameTitle="X-Men" ReleaseDate="1993" Platform="Sega Genesis" />
  • 谢谢,但它什么时候是 xml 文件中的属性?
【解决方案2】:

您需要FirstOrDefault 而不是Select。试试这个来代替 Select:

.FirstOrDefault(e => e.Attribute("id") == "665")

只需将 665 部分替换为您想要的 id#。

编辑:查看 StuartLC 的答案和提供的 xml 文件。我忽略了你使用的简单设计。您尝试获取的数据确实是元素,而不是属性。因此,您需要将 Attribute 调用替换为 Element,如下所示:

.FirstOrDefault(e => e.Element("id") == "665")

顺便说一句,Elements 的返回值是一个 IEnumerable<XElement>,它允许您迭代其中的值。

编辑:这将返回包含所需数据的XElement。此时,您可以使用 StuartLC 的答案将数据传输到您的班级。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2020-06-16
    • 2018-05-21
    • 2021-11-23
    • 1970-01-01
    相关资源
    最近更新 更多