Hello,
I'm new to C#, and just started using XmlElement and its SelectSingleNode method. In my XML file there's a tag that may have a value (i.e. <tag>value</tag>
) or be empty (i.e. <tag></tag>
). If it's empty, SelectSingleNode returns null.
I'm currently using the following code to catch the value of the tag:
XmlElement elem = ....
string s = elem.SelectSingleNode("somepath").Value;
This code obviously raises 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 call to SelectSingleNode with try...catch seems a huge waste of code (I have many fields that may be empty), and I'm sure there's a better way to achieve this.
What is the recommended approach?
EDIT:
Following requests, a sample XML code will be:
<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>
The CS code:
XmlDocument doc = new XmlDocument();
doc.Load("name.xml");
foreach (XmlElement elem in doc.SelectNodes("Elements/Element"))
{
myvalue = elem.SelectSingleNode("Type/text()").Value;
}