Skip item if null for xml text writer

617 views Asked by At

I have Windows form C# application that takes values from the GUI and uses XML Textwriter to create an XML file from them. The problem is some of these values are meant to be optional and when the user leaves them blank, the application gets a null reference exception because the text stream is null. Without doing a check on every value, is there a way to exception handle the whole thing to ignore null values? Try-catch doesn't seem work in this regard because it won't return the cursor to the next statement. Sorry if this is a n00bish question!

2

There are 2 answers

0
Paul Alexander On

Using exceptions to handle this will lead to all sorts of issues. You need to spend the time to wrap the calls to writer.Write(....) with if(...) for values that are not required.

0
Simon Mourier On

Maybe you could use a C# class that represents the data what you want to save, and an XmlSerializer to serialize all this (with an XmlTextWriter as an input) because Xml Serialization handles null implicitely gracefully.