Share via


How to check if XML node exists

Question

Friday, September 27, 2013 9:46 AM

Hi,

when you use:

collection.Asset.Add(c.Element("Asset").Value);

It will error if the actualy <node> is not there, which in this case it may or may not be.

How do you do a simple check for this. Can null coelesense be used. Tried it but couldnt get it to work, may have been the syntax,

Thanks.

All replies (2)

Saturday, September 28, 2013 10:10 AM ✅Answered

Can't you do..

var asset = c.Element("Asset");

if(asset!=null)

{

collection.Asset.Add(asset.Value);

}


Sunday, September 29, 2013 9:42 PM ✅Answered

Here is a little example that select a specified XmlNode:

using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
      XmlDocument doc = new XmlDocument();
      doc.Load("booksort.xml");

      //Select the book node with the matching attribute value.
      XmlNode nodeToFind;
      XmlElement root = doc.DocumentElement;

      // Selects all the title elements that have an attribute named lang
      nodeToFind = root.SelectSingleNode("//title[@lang]");

      if( nodeToFind != null )
      {
           // It was found, manipulate it.
      }
      else
     {
           // It was not found.
      }
  }
}