Xerces-C validate xml with hardcoded xsd

半腔热情 提交于 2019-11-28 13:03:40

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] <files>
Options:
  --help                 Print usage information and exit.
  --verbose              Print progress information.
  --output-dir <dir>     Write generated files to <dir>.
  --hxx-suffix <sfx>     Header file suffix instead of '-schema.hxx'.
  --cxx-suffix <sfx>     Source file suffix instead of '-schema.cxx'.
  --array-name <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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!