1

I am trying to read values from xml using xpath. I already created XmlNamespaceManager and added all prefix,uri pairs to it using my xml file.

I have set of xpaths with me, I need to traverse all xpaths and search relevant data from xml.

I am using below code

if (myXmlDocument.DocumentElement != null)
{
    var selectSingleNode = myXmlDocument.DocumentElement.SelectSingleNode(xPath, myNamespaceManager);
    if (selectSingleNode != null) 
        value = selectSingleNode.InnerText; 
}

My problem is – when I pass such xpath whose prefix is not covered within xml (so my namespaceManager does not contain its prefix or namespace), It will throw an exception “Namespace prefix ‘XXX’ is not defined.”

I just want to skip such unexpected xpaths.

Is there any good solution for that?

Nilesh Thakkar
  • 1,442
  • 4
  • 25
  • 36

1 Answers1

2

As a quick fix, I am using try catch and checking if exception is of type XPathException and message contains “Namespace prefix * is not defined” then skip it, but I really don’t like this.

Nilesh Thakkar
  • 1,442
  • 4
  • 25
  • 36