When reading an XML file into C# i can parse everything as long as the XML file has a Node/Element named Note. I need a way to read xml to see if Note exists and then do something else do something else. Any help would be greatly appreciated.
I have tried different code however they all have given me errors:
XmlNodeList elements = elmRoot.GetElementsByTagName("Node");
Boolean found = false;
foreach(XmlElement element in elements)
{
if(element.Name == Note)
{
found = true;
break;
}
}
Naimish MakwanaPosted Jan 30, 2023, 4:58 AM
Hi Philip,
You could check as below if XML node exists.
Thanks
Anupam MaitiPosted Jan 29, 2023, 6:15 PM
Example 1 :
You can use xmldocument.DocumentElement.SelectNodes("Note");
Example 2:
You can also use
XmlDocument.SelectSingleNode()method which returns the first matching node or null if no match is found.NOTE : In the XPath expression "//Note" is used to select all "Note" nodes in the XML document, regardless of their location in the tree.
Muhammad Imran AnsariPosted Jan 29, 2023, 5:05 PM
Hi Philip,
In your above code, first thing is Element.Node is type of string and not sure what the type of Node is, that could be an error.
Secondly, you can use the XmlDocument class to load and navigate an XML document. To check if a specific node exists, you can use the SelectSingleNode() method. This method takes a string argument that represents the XPath of the node you want to find.
Here is an example: