I am new to C # and just started using XmlElement and its SelectSingleNode method. My XML file has a tag that can have a value (i.e. <tag>value</tag> ) or be empty (i.e. <tag></tag> ). If it is empty, SelectSingleNode returns null.
I am currently using the following code to catch the value of a tag:
XmlElement elem = .... string s = elem.SelectSingleNode("somepath").Value;
This code obviously throws an exception for empty tags. However, for me, an empty tag is a valid value, where I expect the value of my string to be "".
Wrapping each SelectSingleNode call with try ... catch seems like a huge waste of code (I have many fields that may be empty), and I'm sure there is a better way to achieve this.
What is the recommended approach?
EDIT:
As requested, an example XML code would look like this:
<Elements> <Element> <Name>Value</Name> <Type>Value</Type> <-- may be empty <Color>Value</Color> </Element> <Element> <Name>Value</Name> <Type>Value</Type> <Color>Value</Color> </Element> </Elements>
CS Code:
XmlDocument doc = new XmlDocument(); doc.Load("name.xml"); foreach (XmlElement elem in doc.SelectNodes("Elements/Element")) { myvalue = elem.SelectSingleNode("Type/text()").Value; }
c # xml
Roee adler
source share