Xerces-C validate xml with hardcoded xsd

前端 未结 1 1831
误落风尘
误落风尘 2020-12-11 11:56

I\'m writing a library which takes xml files and parses them. To prevent users from feeding inalid xmls into my application i\'m using xerces to validate the xml files via a

1条回答
  •  醉梦人生
    2020-12-11 12:36

    I'll describe three ways of how to hardcode your XSD in your program:

    • by loading the XSD from a file path (this is what your example program does right now)
    • by loading the XSD from a string (this is what you ask for)
    • by loading the XSD from a precompiled binary

    Loading the XSD from a file path

    Boris Kolpackov suggests in a blog post that applications should provide the XSD schema files by themselves rather than looking up the schema files through the xsi:schemaLocation or xsi:noNamespaceSchemaLocation attributes found in the XML file.

    In the blog post there is a link to load-grammar-dom , an example program (put in the public domain) that makes use of the xercesc::DOMLSParser::loadGrammar function:

    user@linux:~$ load-grammar-dom
    usage: load-grammar-dom [test.xsd ... ] [test.xml ...]
    user@linux:~$ 
    

    Loading the XSD from a string

    If you would like to pass the XSD file contents as a string, you would need to use another overload of xercesc::DOMLSParser::loadGrammar where you pass

    const DOMLSInput *source

    instead of

    const char *const systemId

    The DOMLSInput could be created with the help of xercesc::MemBufInputSource and xercesc::Wrapper4InputSource like this

    xercesc::Wrapper4InputSource source(
        new xercesc::MemBufInputSource(
           (const XMLByte *) (a_XsdText.c_str()),
        a_XsdText.size(),
        "A name");
    

    (Adapted somewhat from https://stackoverflow.com/a/15829424/757777 but untested)

    Loading the XSD from a precompiled binary

    Included in the software CodeSynthesis XSD the embedded example (that is put in the public domain) demonstrates how to use

    xercesc::BinInputStream and xercesc::XMLGrammarPool::deserializeGrammars

    to load a precompiled XSD schema.

    See also README.

    The example contains the program xsdbin that compiles XSD schema files into a binary file.

    user@linux:~$ xsdbin --help
    Usage: xsdbin [options] 
    Options:
      --help                 Print usage information and exit.
      --verbose              Print progress information.
      --output-dir      Write generated files to .
      --hxx-suffix      Header file suffix instead of '-schema.hxx'.
      --cxx-suffix      Source file suffix instead of '-schema.cxx'.
      --array-name     Binary data array name.
      --disable-multi-import Disable multiple import support.
    user@linux:~$
    

    In the makefile the XSD schema file is precompiled by xsdbin and the result ends up inside the example executable.

    0 讨论(0)
提交回复
热议问题