Search code examples
xmlxpathnamespacesmsxml

XML Namespace, can not select nodes


I have this xml:

<?xml version="1.0" encoding="utf-8" ?>  
    <ArrayOfFileInformation xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://tempuri.org/">  <Data> ......

When I leave "xmlns="http://tempuri.org/" in the Xml, the following doesn't return any nodes:

CString tag = L"//Data";
MSXML2::IXMLDOMNodeListPtr pDataTag = pXMLDocument->selectNodes((_bstr_t)tag);

When I remove the attribute, everything works fine though.

Can you please help me?


Solution

  • In order to select namespaced nodes in XPath you need to use the facility provided by your XPath library to bind a prefix to the relevant namespace URI, and then use that prefix when selecting nodes by name. The MSDN documentation for the selectNodes method has a C++ example of just this, the key is to set the SelectionNamespaces property on the document

    pXMLDocument->setProperty("SelectionNamespaces", "xmlns:tmp='http://tempuri.org/'");
    

    which will then allow you to use an XPath of //tmp:Data