c++中使用xercesc对xml进行schema校验

头文件

#pragma once

#if !defined(AFX_A1CONTENTHANDLER_H__E0CFBC18_CCC1_42F3_B0A4_B03331AB9693__INCLUDED_)
#define AFX_A1CONTENTHANDLER_H__E0CFBC18_CCC1_42F3_B0A4_B03331AB9693__INCLUDED_
#include <xercesc/sax2/DefaultHandler.hpp>
#include <xercesc/sax/SAXException.hpp>
#include <iostream>

using namespace std;
using namespace xercesc;
class OperContentHandler :
public DefaultHandler
{
public:
OperContentHandler();
virtual ~OperContentHandler();
void characters
(
const XMLCh* const chars,
const XMLSize_t length
);
void endElement
(
const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname
);

virtual void startElement
(
const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname,
const Attributes& attrs
);

// 继承自default Handle, 用于对错误的处理
void error(const SAXParseException& exc)
{
throw exc;
}
void fatalError(const SAXParseException& exc)
{
throw exc;
}
void warning(const SAXParseException& exc)
{
throw exc;
}

wstring goods;

};
#endif // !defined(AFX_A1CONTENTHANDLER_H__E0CFBC18_CCC1_42F3_B0A4_B03331AB9693__INCLUDED_)

cpp文件

// OperContentHandler.cpp: derived class from SAXContentHandlerImpl


#include "OperContentHandler.hpp"


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

OperContentHandler::OperContentHandler()
{
}

OperContentHandler::~OperContentHandler()
{
//object destruction is handled by the Release() impl of parent class
}

void OperContentHandler::startElement
(
const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname,
const Attributes& attrs
)
{
wstring sNodeName = localname;
goods += sNodeName;
}
void OperContentHandler::endElement( const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname )
{
wstring sNodeName = localname;
goods += sNodeName;
}
void OperContentHandler::characters( const XMLCh* const chars,
const XMLSize_t length )
{
wstring sNodeValue(chars);
goods += sNodeValue;
}

头文件

#pragma once
#ifndef _OPSMGRXMLVALIDATOR__H_
#define _OPSMGRXMLVALIDATOR__H_

#include "xercescsax2XMLReaderFactory.hpp"
#include "OperContentHandler.hpp"
#include<boost/filesystem/config.hpp>
#include <3rd/boost/filesystem.hpp>
#include<sstream>

struct ERRORCODE
{
std::wstring wstrCol;
std::wstring wstrRow;
std::wstring wstrErrorMessage;
};

class OPSXMLValidator
{
public:
OPSXMLValidator();
~OPSXMLValidator();
private:
void GetSchemaPath(std::string strSchemaSrcPath);
private:
OperContentHandler * m_handler;
SAX2XMLReader* m_parser;
Grammar * m_grammar;
int m_iErrorCol;
int m_iErroRow;
std::wstring m_wstrErrorMessage;
std::string m_strSchemaParentPath;
std::string m_strSchemaPath;
public:
//接口
int ParseXML(std::string strPath);
int GetTheErrorState(std::wstring& wstrErrorCol, std::wstring &wstrErrorRow, std::wstring &wstrErrorMessage);
};
#endif

cpp文件

#include"opsMgrXMLValidator.h"
#include<boost/filesystem/config.hpp>
#include <3rd/boost/filesystem.hpp>
using namespace xercesc;

OPSXMLValidator::OPSXMLValidator():
m_handler(NULL),
m_parser(NULL),
m_grammar(NULL),
m_iErrorCol(0),
m_iErroRow(0),
m_strSchemaPath(""),
m_strSchemaParentPath(""),
m_wstrErrorMessage(L"")
{
XMLPlatformUtils::Initialize();
m_handler = new OperContentHandler;
m_parser = XMLReaderFactory::createXMLReader();
GetSchemaPath("");
if(m_strSchemaPath.empty())
{
std::cout << " error:the sechema path is empty."<<std::endl;
}
// m_grammar = m_parser->loadGrammar(m_strSchemaPath.c_str(), Grammar::SchemaGrammarType, true);
m_parser->setFeature(XMLUni::fgSAX2CoreValidation, true);

m_parser->setFeature(XMLUni::fgXercesSchema, true);
m_parser->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true);
m_parser->setFeature(XMLUni::fgXercesContinueAfterFatalError, false);

m_parser->setContentHandler(m_handler);
m_parser->setErrorHandler(m_handler);
}

OPSXMLValidator::~OPSXMLValidator()
{
if(NULL != m_handler)
{
delete m_handler;
}
if(NULL != m_grammar)
{
delete m_grammar;
}
if(NULL != m_parser)
{
delete m_parser;
}
XMLPlatformUtils::Terminate();
}

void OPSXMLValidator::GetSchemaPath(std::string strSchemaSrcPath)
{
if(!strSchemaSrcPath.empty())
{
m_strSchemaPath = strSchemaSrcPath;
return ;
}
boost::filesystem::path CurrentPath = boost::filesystem::current_path();
boost::filesystem::path SchemaPath = CurrentPath.parent_path().parent_path();
SchemaPath.append("\data\schema");
if(!boost::filesystem::exists(SchemaPath))
{
// the schema path is not exist.
return ;
}
m_strSchemaPath = SchemaPath.string().c_str();
SchemaPath = SchemaPath.parent_path();
m_strSchemaParentPath = SchemaPath.string().c_str();
boost::filesystem::path TargetPath(m_strSchemaParentPath);
TargetPath.append("/temp");
if(!boost::filesystem::exists(TargetPath))
{
boost::filesystem::create_directory(TargetPath);
}
TargetPath.append("/xml");
if(!boost::filesystem::exists(TargetPath))
{
boost::filesystem::create_directory(TargetPath);
}
}
int OPSXMLValidator::ParseXML(std::string strPath)
{
int errorIndex = 0;
std::string fileName;
boost::filesystem::path TargetPath(m_strSchemaParentPath);
try
{

boost::filesystem::path ResourcePath(strPath.c_str());
fileName = ResourcePath.filename().string().c_str();

TargetPath.append("/temp/xml/");
TargetPath.append(fileName.c_str());
if(boost::filesystem::exists(TargetPath))
{
boost::filesystem::remove(TargetPath);
}
boost::filesystem::copy_file(ResourcePath, TargetPath);
TargetPath.normalize();

m_parser->parse(TargetPath.wstring().c_str());
}
catch(const SAXParseException& toCatch)
{
m_iErrorCol = (int) toCatch.getColumnNumber();
m_iErroRow = (int) toCatch.getLineNumber();
m_wstrErrorMessage = toCatch.getMessage();
errorIndex = -1;
}
catch(const XMLException & xe)
{
m_wstrErrorMessage = xe.getMessage();
errorIndex = -1;
}
if(boost::filesystem::exists(TargetPath))
{
boost::filesystem::remove(TargetPath);
}
return errorIndex;
}

int OPSXMLValidator::GetTheErrorState(std::wstring &wstrErrorCol, std::wstring &wstrErrorRow, std::wstring &wstrErrorMessage)
{
int iRet = 0;
wstringstream iTows;
if(0 != m_iErrorCol || 0 != m_iErroRow)
{
iTows << m_iErrorCol;
iTows >> wstrErrorCol;
iTows.clear();
iTows << m_iErroRow;
iTows >> wstrErrorRow;
wstrErrorMessage = m_wstrErrorMessage.c_str();
}
return iRet ;
}

原文地址:https://www.cnblogs.com/zhangdewang/p/8134460.html