xerces-c是一个可以校验XML合法性的XML解析器,它的语言是C++,它的官方主页:http://xml.apache.org/xerces-c。它支持下面这些标准:XML 1.0 ,XML 1.1 ,DOM 1, 2, 3 , SAX 1.0 和SAX 2.0, XML Schema。
xerces操作XML主要是分几步:
用一个例子来演示一下:
address.xml:
<?xml version="1.0" encoding="utf-8"?> <Address> <Recipient>Mr. Walter C. Brown</Recipient> <House>49</House> <Street>Featherstone Street</Street> <Town>LONDON</Town> <PostCode>EC1Y 8SY</PostCode> <Country>UK</Country> </Address>
#include <stdio.h> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/sax/SAXException.hpp> #include <xercesc/dom/DOMException.hpp> #include <xercesc/dom/DOMElement.hpp> #include <xercesc/dom/DOMLSException.hpp> using namespace XERCES_CPP_NAMESPACE; int main(int argc, char* argv[] ) { if ( argc < 2 ) { printf( "must specify a file\n" ); return -1; } XMLPlatformUtils::Initialize(); XercesDOMParser parser; try { parser.parse( argv[1] ); } catch ( SAXException& e ) { printf( "msg:%s\n", XMLString::transcode(e.getMessage() ) ); return -2; } catch ( XMLException& e ) { printf( "code:%d, msg:%s\n", e.getCode(), XMLString::transcode( e.getMessage() ) ); return -3; } catch ( DOMException& e ) { printf( "code:%d, msg:%s\n", e.code, e.msg ); return -4; } DOMDocument* pDoc = NULL; try { pDoc = parser.getDocument(); } catch ( DOMLSException& e ) { printf( "code:%d, msg:%s\n", e.code, e.msg ); return -5; } catch ( DOMException& e ) { printf( "code:%d, msg:%s\n", e.code, e.msg ); return -6; } DOMElement* root = pDoc->getDocumentElement(); if ( root == NULL ) { return -7; } DOMElement* child = root->getFirstElementChild(); XMLSize_t cnt = root->getChildElementCount(); for ( XMLSize_t i = 0; i < cnt; i++ ) { char* name = XMLString::transcode( child->getTagName() ); printf( "%s=", name ); XMLString::release( &name); char* value = XMLString::transcode(child->getTextContent()); printf( "%s\n", value ); XMLString::release( &value ); child = child->getNextElementSibling(); } return 0; }
[xuzhina@localhost sample]$ g++ -g -o address address.cpp -lxerces-c
[xuzhina@localhost sample]$ ./address address.xml Recipient=Mr. Walter C. Brown House=49 Street=Featherstone Street Town=LONDON PostCode=EC1Y 8SY Country=UK
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/xuzhina/article/details/46813853