Search code examples
c++xmlxsdxerces-c

How to retrieve xsi:schemaLocation with xercesc::SAX2XMLReader


I use a SAX2XMLReader to parse an XML file that specifies an XSD schema by having the attribute xsi:schemaLocation in its root element.

How can I retrieve the string value of this attribute?

I tried

parser->getProperty(XMLUni::fgXercesSchemaExternalSchemaLocation)

but it returns a nullptr.


Solution

  • You could create a class MyPSVIHandler that inherits from PSVIHandler and install it with the setPSVIHandler method.

    MyPSVIHandler psvi_handler;
    sax2xmlreader->setPSVIHandler(&psvi_handler);
    
    void MyPSVIHandler::handleAttributesPSVI(
        const XMLCh *const /* localName */,
        const XMLCh *const /* uri */,
        PSVIAttributeList *psviAttributes) {
      for (XMLSize_t i = 0; i < psviAttributes->getLength(); i++) {
        if (XMLString::equals(psviAttributes->getAttributeNamespaceAtIndex(i),
                              SchemaSymbols::fgURI_XSI)) {
          const XMLCh *attr_name(psviAttributes->getAttributeNameAtIndex(i));
          if (XMLString::equals(attr_name, SchemaSymbols::fgXSI_SCHEMALOCATION)) {
            const XMLCh *str = psviAttributes->
                getAttributePSVIAtIndex(i)->getSchemaNormalizedValue();
            char *transcoded_str = xercesc::XMLString::transcode(str);
            std::cout << "schemaLocation = " << transcoded_str << "\n";
            xercesc::XMLString::release(&transcoded_str);
          }
        }
      }
    }