XmlDocument element checking

  • Thread starter Thread starter David Dvali
  • Start date Start date
D

David Dvali

How can I check if the XmlDocument contains some element?
For example:
<root>
<elem1>
<optional>
Some data
<optional>
</elem1>
</root>
How can I check if the XmlDocument contains "optional" element?
 
Hi David,
you could explicitly check for the node like:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("xmlfile.xml");

if(xmlDoc.DocumentElement.FirstChild.FirstChild == null)
{
//optional node is not there
}

or you can use XPath (see http://www.w3.org/TR/xpath) to find the node:

if(xmlDoc.SelectSingleNode("/root/elem1/optional") == null)
{
//optional node is not there
}


Hope that helps
Mark R Dawson.
 
Back
Top