本文主要是介绍使用xerces-c++库编写XSD校验XML的类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
由于需要写个XSD来校验XML功能的类, 上网搜索了很多资料, 都不能完全满足需要, 于是在多方参考了网络上的文章后, 自己进一步改进了一下。
直接贴代码,备忘。
相关库的官方说明地址: http://xerces.apache.org/xerces-c/
----------------------------------------------------------------------
头文件 IXMLValidation.h
#ifndef _IXML_VALIDATION_H_
#define _IXML_VALIDATION_H_
#include <iostream>
#include <list>
#include <string>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/framework/XMLGrammarDescription.hpp>
#include <xercesc/sax/ErrorHandler.hpp>
#include <xercesc/sax/SAXParseException.hpp>
using std::cerr;
using std::endl;
XERCES_CPP_NAMESPACE_USE
class StrX
{
char* fLocalForm;
public :
StrX(const XMLCh* const toTranscode) { fLocalForm = XMLString::transcode(toTranscode); }
~StrX() { XMLString::release(&fLocalForm); }
const char* localForm() const { return fLocalForm; }
};
class DOMTreeErrorReporter : public ErrorHandler
{
public:
DOMTreeErrorReporter();
virtual ~DOMTreeErrorReporter();
void warning(const SAXParseException& toCatch) {}
void resetErrors() {}
void error(const SAXParseException& toCatch);
void fatalError(const SAXParseException& toCatch);
bool getErrFlag(){ return m_errFlag; }
std::string getErrMsg(){ return m_errMsg; }
private:
std::string m_errMsg;
bool m_errFlag;
};
class IXMLValidation
{
public:
IXMLValidation(std::string& grammar);
~IXMLValidation();
int validation(std::string & xmlStr,std::string &errMsg);
sprivate:
std::string m_grammar;
};
#endif
----------------------------------------------------------------------------------------
代码文件 IXMLValidation.cpp
#include "IXMLValidation.h"
#include <fstream>
#include <unistd.h>
#include <memory>
#include <sstream>
#include <xercesc/framework/MemBufInputSource.hpp>
std::ostream&
operator<<(std::ostream& target, const StrX& toDump)
{
target << toDump.localForm();
return target;
}
DOMTreeErrorReporter::DOMTreeErrorReporter()
{
m_errFlag = false;
}
DOMTreeErrorReporter::~DOMTreeErrorReporter()
{
}
void DOMTreeErrorReporter::error(const SAXParseException& toCatch) {
//cerr << "Error at file /"" << StrX(toCatch.getSystemId())
// << "/", line " << toCatch.getLineNumber()
// << ", column " << toCatch.getColumnNumber() << endl
// << " Message: " << StrX(toCatch.getMessage()) << endl;
std::ostringstream os;
os << "Error at " << StrX(toCatch.getSystemId())
<< ". line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< ", Message: " << StrX(toCatch.getMessage()) << endl;
m_errMsg += os.str();
m_errFlag = true;
}
void DOMTreeErrorReporter::fatalError(const SAXParseException& toCatch) {
//cerr << "Fatal Error at file /"" << StrX(toCatch.getSystemId())
// << "/", line " << toCatch.getLineNumber()
// << ", column " << toCatch.getColumnNumber() << endl
// << " Message: " << StrX(toCatch.getMessage()) << endl;
std::ostringstream os;
os << "Fatal Error at " << StrX(toCatch.getSystemId())
<< ". line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< ", Message: " << StrX(toCatch.getMessage()) << endl;
m_errMsg += os.str();
m_errFlag = true;
}
IXMLValidation::IXMLValidation(std::string& grammar)
:m_grammar(grammar)
{
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& e)
{
StrX tmp_e(e.getMessage());
cerr << "Xerces initialization error: " << tmp_e.localForm() << endl;
throw; //return 2;
}
}
IXMLValidation::~IXMLValidation()
{
}
int IXMLValidation::validation(std::string & xmlStr,std::string &errMsg)
{
int result;
std::auto_ptr<XercesDOMParser > parser(new XercesDOMParser);
std::auto_ptr<DOMTreeErrorReporter> errReporter( new DOMTreeErrorReporter);
parser->setErrorHandler(&(*errReporter));
parser->setDoNamespaces(true);
parser->setCreateEntityReferenceNodes(true);
parser->useCachedGrammarInParse(true);
parser->setDoSchema(true);
//parser->setDoValidation(true); //deprecated
parser->setValidationScheme(AbstractDOMParser::Val_Always);
parser->setValidationSchemaFullChecking(true);
MemBufInputSource inputSrc((XMLByte*)m_grammar.c_str(), (XMLSize_t)m_grammar.length(), "xsd");
if ( parser->loadGrammar(inputSrc, Grammar::SchemaGrammarType, true) == 0 )
{
errMsg = "Error loading grammar " ;
return 4;
}
char xml_fname[100];
result = 1;
try
{
MemBufInputSource inputXml((XMLByte*)xmlStr.c_str(),(XMLSize_t)xmlStr.length(), "xml");
parser->parse(inputXml);
result = errReporter->getErrFlag() ? 9 : 0; // 0 成功, !0 失败
errMsg = errReporter->getErrMsg();
}
catch ( const OutOfMemoryException& )
{
errMsg = "Out of memory exception." ;
}
catch ( const XMLException& e )
{
std::ostringstream os;
os << "An error occurred during parsing, Message: " << StrX(e.getMessage()) ;
errMsg = os.str();
}
catch ( const DOMException& e )
{
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
std::ostringstream os;
os << "DOM Exception code is: " << e.code << ". ";
if ( DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars) )
os << "Message is: " << StrX(errText);
errMsg = os.str();
}
catch (...)
{
errMsg = "An error occurred during parsing.";
}
return result;
}
------------------------------------------------------------------
使用举例: main.cpp
#include "IXMLValidation.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
std::ifstream of("test.xsd");
std::string xsdStr ;
char *s = NULL;
int n;
of.seekg(0, ios::end);
n = of.tellg(); // 文件大小
s = new char[n+1];
of.seekg(0, ios::beg);
of.read(s, n);
s[n] = '/0';
xsdStr = s;
of.close();
IXMLValidation xmlValid(xsdStr);
std::ifstream of2("test.xml");
std::string xmlStr ;
of2.seekg(0, ios::end);
n = of2.tellg(); // 文件大小
delete s;
s = new char[n+1];
of2.seekg(0, ios::beg);
of2.read(s, n);
s[n] = '/0';
xmlStr = s;
of2.close();
std::string errMsg;
int ret = xmlValid.validation(xmlStr,errMsg);
cout << ret << endl;
if( ret )
cout << "validation fail:" << endl << errMsg << endl;
else
cout << "validation success." << endl;
return 0;
}
这篇关于使用xerces-c++库编写XSD校验XML的类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!