c# XML check if node is not null or child of node is not null

mion shion 241 Reputation points
2021-03-22T17:55:21.937+00:00

ok sorry to post again with xml question i quite new to parsing xml documents been looking through guides and stuff but can't seem to get this working so i have the following code here

        public void test()
        {
            //elfdb = new DB_GET();
            //elfdb.ParseXML(@"C:\Users\elfen\AppData\Local\PCDJ-DEX3\Database\Database.xml");


            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:\Users\elfen\AppData\Local\PCDJ-DEX3\Database\Database.xml");

            XmlNodeList nodes = doc.SelectNodes("/database/tracks/track");
            foreach (XmlNode node in nodes)
            {
                //string trackID = node.Attributes[0].InnerXml;
                //string Artist = node.Attributes[1].InnerXml;
                //string Title = node.Attributes[2].InnerXml;

                string MusicPath = node.Attributes["fnam"].Value;

                if (node.Attributes["arti"].Value != null)
                {
                    Artist = node.Attributes["arti"].Value;
                }
                else
                {

                    Titel = node.Attributes["titl"].Value;
                    paths.Add(MusicPath);
                }

            }

            checkfiles();

        }

issue im having is the Artist node keeps returning null ( yes i have looked there are a couple of songs that don't have an artist so can see why the null exception occurs )

the issue im having is i am trying to create an if function,

and i get returned null object is not an instance of an object.

tryied many ways,

node.Attributes["arti"].Value != null

bool testbool = node.Attributes["arti"].Value == 0

then passed testbool to the if statement but still same error

so thought maybe if(nodes != null)

but still the same issue does not register as a null value and was thinking not best method where i use xpath its going to never be null

so here i am again asking for guidance sorry to ask a lot of questions,

Kind Regards,
elfenliedtopfan5

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,278 questions
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,576 Reputation points
    2021-03-23T06:44:32.883+00:00

    You can use node.Attributes["arti"]!= null instead of node.Attributes["arti"].Value != null.

    When the current node does not contain arti, then node.Attributes["arti"] is already null, and node.Attributes["arti"].Value is equivalent to null.Value, which is the cause of NullReferenceException.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Yitzhak Khabinsky 25,106 Reputation points
    2021-03-22T20:59:44.21+00:00

    Hi @mion shion ,

    I got your XML file from your previous post. You always need to provide all artifacts that are needed for a minimal reproducible example.

    It is better to use LINQ to XML API. It is available in the .Net Framework since 2007.

    Please see below how to handle XML attributes properly. This code will never bomb with an exception for a missing attribute.

    c#

    void Main()  
    {  
     const string fileName = @"e:\Temp\mionshion-3520.xml";  
      
     XDocument xdoc = XDocument.Load(fileName);  
     // id="29971" and id="29973" don't have @arti attribute  
     List<string> ListOfTrackIDs = new List<string> {"29971", "29973", "29985"};  
      
     foreach (XElement xelem in xdoc.Descendants("track")  
     .Where(x => ListOfTrackIDs.Contains((string)(x.Attribute("id")))))  
     {  
     Console.WriteLine("trackID: '{0}', Artist: '{1}', Title: '{2}'"  
     , xelem.Attribute("id")?.Value  
     , xelem.Attribute("arti")?.Value  
     , xelem.Attribute("titl")?.Value);  
     }  
    }  
    

    Output

    trackID: '29985', Artist: 'Calum Scott', Title: 'You are the Reason'  
    trackID: '29971', Artist: '', Title: 'Special Nightcore Mix for Gaming (Rebirth) (1)'  
    trackID: '29973', Artist: '', Title: 'Better Off Alone'  
    
    1 person found this answer helpful.