Check a Node in XML Doc in C#

RadhaKrishnaKiJaya
RadhaKrishnaKiJaya used Ask the Experts™
on
Hello Experts,
I have an XML Document named ErrorRowsXml as below.  I need to check the existence of the node ERROR_DETAIL in C#.  How can I do that.

Thank you very much in advance.

- <ERROR_REPORT>
- <ERRORS STATUS="TRUE">
  <ERROR CODE="" DESC="" />
  </ERRORS>
  <ERROR_DETAIL FIELD_NO="" ERROR_MESSAGE="" FIELD_NAME="" />
</ ERROR_REPORT >
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Here's a quick and basic example:

void CheckXmlFile(string xmlFile)
{
    // Create an XmlDocument
    XmlDocument xmlDoc = new XmlDocument();

    // Load in your file
    xmlDoc.Load(xmlFile);

    // Select the ERROR_DETAIL node
    XmlNode errorDetail = xmlDoc.DocumentElement.SelectSingleNode("ERROR_DETAIL");

    // Check if the node exists
    if (errorDetail != null)
    {
        // Loop through the node's attributes
        foreach (XmlAttribute att in errorDetail.Attributes)
            Console.WriteLine($"Name {att.Name} | Value {att.Value}");
    }
    else
    {
        // There was no ERROR_DETAIL node
        MessageBox.Show("No ERROR_DETAIL node!");
    }
}

Open in new window

The easiest way is to use the SelectSingleNode() method:
            XmlDocument xml = new XmlDocument();
            xml.Load( "ErrorRowsXml.xml" );
            if( xml.SelectSingleNode( "/ERROR_REPORT/ERROR_DETAIL" ) != null ) 
                Console.WriteLine("Exists");
            else
                Console.WriteLine("Does not exist");

Open in new window

Author

Commented:
Chris Stanyon and zc2,
Thank you for your time and help.  

I am able to check it.  Now, once checked, if null I need to add the node.  How can I do that?

Thank you
Could by done like the following:
 ....           
            else {
                Console.WriteLine("Does not exist");
                XmlElement ed = xml.CreateElement("ERROR_DETAIL");
                ed.SetAttribute( "FIELD_NO", "" );
                ed.SetAttribute( "ERROR_MESSAGE", "" );
                ed.SetAttribute( "FIELD_NAME", "" );
                xml.DocumentElement.AppendChild( ed );
            }

Open in new window

Author

Commented:
Thank you Chris Stanyon and zc2 for your time and help.  It worked like charm.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial