문제

I have a problem where im trying to get the values from the attributes of a xml file from a url.

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

code:

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; }
}

I hope there is someone that can help me, thanks.

도움이 되었습니까?

해결책

id, GameTitle, ReleaseDate and Platform are all elements under Game, viz:

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

You'll also need to parse the int.

다른 팁

You need FirstOrDefault instead of Select. Try this in place of Select:

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

Just replace the 665 portion with the id# you want.

EDIT: in looking at StuartLC's answer and the provided xml file. I overlooked the simple design that you used. The data that you are trying to get are indeed elements, not attributes. So you would need to replace the Attribute call to Element like so:

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

On a side note, the return value of Elements is an IEnumerable<XElement> which allows you to iterate over the values within it.

EDIT: This will return the XElement containing the desired data. At this point, you can use StuartLC's answer to transfer the data into your class.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top