Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# XmlElement: SelectSingleNode returns null for empty string?

Tags:

c#

xml

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;
}
like image 834
Roee Adler Avatar asked Jul 23 '09 17:07

Roee Adler


1 Answers

Your sample code:

  myvalue = elem.SelectSingleNode("Type/text()").Value;

is where the problem is. The XPath expression you've used there doesn't mean "give me text of element Type". It means "give me all child text nodes of element Type". And an empty element doesn't have any child text nodes (a text node cannot be empty in XPath document model). If you want to get text value of the node, you should use:

  myvalue = elem.SelectSingleNode("Type").InnerText;
like image 191
Pavel Minaev Avatar answered Sep 21 '22 10:09

Pavel Minaev