关于SAX的解释,和好处,不做过多的介绍,你完全可以搜索引擎里面找到茫茫多的介绍http://baike.soso.com/v123641.htm?ch=ch.bk.innerlink;
本文的主要目的是介绍如何在自己的C++程序中利用Xerces C++ SAX解析XML文档;
1、Xerces C++下载
首先,我们需要去下载Xerces C++:http://xerces.apache.org/xerces-c/download.cgi
以上连接中给出了各种VS版本的Xerces C++的编译文件和源代码,供你下载使用。
2、在工程中引入Xerces C++
1、C/C++ 常规中:附件包含目录:引入include ;头文件
2、链接器常规中:附件包含目录:引入lib;bin;文件
3、链接器输入中:附加依赖项:引入:xerces-c_3.lib xerces-c_static_3.lib
3、OK以上环境搭建好后,开始编码吧
#include <xercesc/util/PlatformUtils.hpp> #include <xercesc/sax2/SAX2XMLReader.hpp> #include <xercesc/sax2/DefaultHandler.hpp> #include <xercesc/sax2/XMLReaderFactory.hpp> #include <xercesc/util/XMLString.hpp> #include <iostream> #include "MySAX2Handler.h" using namespace std; using namespace xercesc_3_1; int main (int argc, char* args[]) { try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); cout << "Error during initialization! :\n"; cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return 1; } char* xmlFile = "x1.xml"; SAX2XMLReader* parser = XMLReaderFactory::createXMLReader(); parser->setFeature(XMLUni::fgSAX2CoreValidation, true); parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true); // optional parser->setFeature(XMLUni::fgXercesDynamic, false); parser->setFeature(XMLUni::fgXercesSchema, true); parser->setFeature(XMLUni::fgXercesSchemaFullChecking, true); MySAX2Handler* defaultHandler = new MySAX2Handler(); parser->setContentHandler(defaultHandler); parser->setErrorHandler(defaultHandler); parser->setEntityResolver(defaultHandler); try { parser->parse(xmlFile); } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return -1; } catch (const SAXParseException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return -1; } catch (...) { cout << "Unexpected Exception \n" ; return -1; } defaultHandler->OutputPsList(); delete parser; delete defaultHandler; XMLPlatformUtils::Terminate(); system("PAUSE"); return 0; }
4、需要自己实现自己的接口:
#pragma once #include<xercesc/sax2/DefaultHandler.hpp> #include <xercesc/sax2/Attributes.hpp> #include "PathsynopsisNode.h" using namespace std; using namespace xercesc_3_1; class MySAX2Handler :public DefaultHandler { public: MySAX2Handler(void); ~MySAX2Handler(void); public: void startElement( const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const Attributes& attrs ); void characters( const XMLCh* const chars , const XMLSize_t length ); void endElement( const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname ); void fatalError(const SAXParseException&); };
需要我们在XML文档的开头添加文档编码方式:<?xml version="1.0" encoding="gb2312" ?>