Avatar of auldh
auldh
 asked on

XML write to console excluding null fields

I got help on reading XML file (Help parsing XML with C#).


Having issues where for example some "controls" may have fewer parameters. I know I can use "if(control.attributes.interrupt.value != null)" before each ConsoleWrite.


Looking for a more elegant way to do this. Preferably in a single line. So if the parameter is null it is not printed and the process continues.



XMLCComponents

Avatar of undefined
Last Comment
auldh

8/22/2022 - Mon
auldh

ASKER
Tried
if (control.attributes.interrupt.value != null)

Open in new window

I get System.NullReferenceException: 'Object reference not set to an instance of an object.' message.
Even tried
try { Console.WriteLine($"control: {control.instance} - {control.attributes.interrupt.value}"); }//might be missing
                        catch (Exception NullReferenceException) { }

Open in new window

Same thing. Clearly not handling the exception right. Now I'm lost.




auldh

ASKER
Well, I figure out that my System.NullReferenceException: 'Object reference not set to an instance of an object.' message. Had to exclude the ".value" in the validation.

Now back to my advice question...
ASKER CERTIFIED SOLUTION
ste5an

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
auldh

ASKER
Sorry about that. In my code I know if a parameter in XML wanting to expose does not exist I can test first to see if it is there, like this:
 if (control.attributes.interrupt != null)
Console.Write($"\t{control.attributes.interrupt.value}");
else
Console.Write("\t");

Open in new window

Repeating this for each parameter. I was wondering/looking for a better/elegant way of doing this, as there are 40 or so values I want to write to the console.
Sometimes as I iterate through all the "controls" in the XML some have the values others don't.

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck