0

I have this XML file:

<?xml version="1.0" encoding="utf-8"?>
<NewSounds>
    <Artists>
      <Artist>Avril Lavigne</Artist>
      <Artist>Bob Marley</Artist>
      <Artist>Coldplay</Artist>
    </Artists>

  <Genres>
    <Genre>Rock</Genre>    
    <Genre>Jazz</Genre>
    <Genre>Metal</Genre>
  </Genres>
</NewSounds>

How do I parse this simple XML file in LINQ? I know very little about LINQ, this is what I have:

var artists = xml.Descendants("Artists")
                    .Elements("Artist")
                    .Select(a => new Artist {
                        Name = a.Element("Artist").Value
                    }).ToArray();

Problem is, it throws up a System.NullReferenceException: Object reference not set to an instance of an object. error on the .Select part (maybe because it can't find the value?).

I'd like to traverse the XML and grab the relevant parts inside the <Artist> and <Genre> tags.

2 Answers 2

7

a in your Select() callback is the <Artist> element. a.Element("Artist") isn't anything.

Sign up to request clarification or add additional context in comments.

Comments

2

Cast element to string, instead of accessing Value property. In this case you will not get exception if element is null:

var artists = xml.Descendants("Artists")
                    .Elements("Artist")
                    .Select(a => new Artist {
                        Name = (string)a.Element("Artist")
                    }).ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.