0

I am new to XML, I need to parse this part of a .XML page:

<TEAMDATA>
<Team TriCode="BOU" ShortName="Bournemouth" LongName="AFC Bournemouth" OfficialName="AFC Bournemouth" ID="t91" Manager="Manager" Venue="Vitality Stadium"/>
<Team TriCode="ARS" ShortName="Arsenal" LongName="Arsenal" OfficialName="Arsenal" ID="t3" Manager="Manager" Venue="Emirates Stadium"/>
<Team TriCode="AVL" ShortName="Aston Villa" LongName="Aston Villa" OfficialName="Aston Villa" ID="t7" Manager="Caretaker Manager" Venue="Villa Park"/>
<Team TriCode="BUR" ShortName="Burnley" LongName="Burnley" OfficialName="Burnley" ID="t90" Manager="Manager" Venue="Turf Moor"/>

My idea is to have the tricode, shortname and logname for each team printed, ex.:

BOU Bournemouth AFC Bournemouth
ARS Arsenal AFC Bournemouth
...

This is the code I have:

static void Main(string[] args)
    {
        string strURL = "http://MyURL.xml";
        XDocument xDoc;
        string title = "";

        xDoc = XDocument.Load(strURL);
        var TeamID = from r in xDoc.Descendants("TEAMDATA")

                     select new
                     {

                         TriCode = r.Attribute("TriCode").Value,
                         ShortName = r.Element("ShortName").Value,
                         LongName = r.Element("LongName").Value,
                     };

        foreach (var r in TeamID)
        {
            Console.WriteLine(r.TriCode + r.ShortName + r.LongName);
        }
    }

Until now I receive the

NullReferenceException exception

after the select new clause. What do I need to parse those lines?

1 Answer 1

1

This should work

 from r in xDoc.Descendants("Team")
                 select new
                 {

                     TriCode = r.Attribute("TriCode").Value,
                     ShortName = r.Attribute("ShortName").Value,
                     LongName = r.Attribute("LongName").Value,
                 };

What is wrong with your code?

xDoc.Descendants("TEAMDATA") returns all those descendants with element name TEAMDATA and that element doesn't have any of the attributes you are looking for.

r.Element("ShortName").Value this must be a typo. What you want was attribute value, but not element itself.

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

1 Comment

Still I have the An unhandled exception of type 'System.NullReferenceException' occurred ..Object reference not set to an instance of an object. This is the most common error and I usually find the cause immediately, In this case I cannot find any.

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.