question

mionshion-3520 avatar image
0 Votes"
mionshion-3520 asked YitzhakKhabinsky-0887 commented

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

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

dotnet-csharp
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@mionshion-3520,

Please edit your post, and add a sample of the input XML.

0 Votes 0 ·
TimonYang-MSFT avatar image
1 Vote"
TimonYang-MSFT answered mionshion-3520 commented

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for response this has resolved the issue in question thank you :)

0 Votes 0 ·
YitzhakKhabinsky-0887 avatar image
1 Vote"
YitzhakKhabinsky-0887 answered YitzhakKhabinsky-0887 commented

Hi @mionshion-3520,

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'
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you for response :) but each xml file is different the reason i done it the way i have is that it needs to loop through each one on different peoples pc's and each person going to have played different songs so those numbers are unique to my list only but am looking into linq to xml as looks more friendly.

0 Votes 0 ·

@mionshion-3520,
In essence, LINQ to XML replaced all previous XML APIs, inclusing the API that you are using.
It happened almost 15 years ago, an eternity in technology.

0 Votes 0 ·