1teamsah
1teamsah

Reputation: 1933

How to know whether xml has any node or not

I've an XML document (Microsoft's Project XML) like this:

<Columns>
  <Column>
    <Name>A</Name>
    <Width>100</Width>
  </Column>
</Columns>
<Columns>
  <Column>
    <Name>B</Name>
    <Width>200</Width>
  </Column>
</Columns>
<Columns>
 <Column>
   <Name>C</Name>
 </Column>
</Columns>

I'm trying to get their Name and Width texts:

var man = new XmlNamespaceManager(xdoc.NameTable);
man.AddNamespace("ns", "http://schemas.microsoft.com/project");

XmlNodeList xnList = xdoc.SelectNodes("/ns:Columns/ns:Column", man);

foreach (XmlNode xn in nodeList[i])
        {
            string name = xn["Name"].InnerText);
            string width = xn["Width"].InnerText);
        }

If the XML has these "Name" and "Width" nodes, there is no problem. But, sometimes like as the last one in above sample has no "Width" node. So I take an error. How can I avoid from this. I want to get it as "empty" string. How can I do?

Upvotes: 0

Views: 54

Answers (1)

Juan
Juan

Reputation: 3705

You can check if it is null:

string name;
if (xn["Name"] == null) 
{
    // Node doesn't exists
    name = string.Empty;
}
else
{
    name = xn["Name"].InnerText;
}  

Or you can do it in just one liner:

string name = xn["Name"] == null ? string.Emtpy : xn["Name"].InnerText;

Or if you are using C# 6 even:

string name =  xn["Name"]?.InnerText;

If there is no node with that name the index property will return null

Upvotes: 2

Related Questions