Search code examples
c#xmldocument

finding a starting point in XmlDocument


So I have this code.

XmlDocument document = new XmlDocument();
document.Load(location);

XmlNodeList msgSigsNodeList;
try
{
    XmlNode msgSigsNode = document.SelectSingleNode("/sometimesHere/message");
    msgSigsNodeList = msgSigsNode.SelectNodes("whatEver");
}
catch
{
    XmlNode msgSigsNode = document.SelectSingleNode("/message");
    msgSigsNodeList = msgSigsNode.SelectNodes("whatEver");
}      

but I don't want to use exceptions I would like to use if statements or better yet is there a way to do this without if statement.


Solution

  • There are two solutions:

    1. You can use XPath that is independent from root: //message (will match any message tag)
    2. Start selecting nodes from document root: document.DocumentElement.SelectSingleNode("/message")