xerces-c用DOM方式操做xml

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。html


xerces操做XML主要是分幾步:apache

  1. 先調用XMLPlatformUtils::Initialize初始化環境,其中最重要是初始化內存管理器。若是沒有調用這個,直接進行下面的步驟,程序會崩潰。
  2. 使用XercesDOMParser::parse方法來解析XML
  3. 使用XercesDOMParser::getDocument來DOMDocument對象指針
  4. 經過調用DOMDocument::getDocumentElement從DOMDocument對象指針裏獲取文檔的主節點的指針,類型爲DOMElement

用一個例子來演示一下:dom


address.xml:spa

<?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>

address.cpp:

#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


本文同步分享在 博客「debugeeker」(CSDN)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。.net

相關文章
相關標籤/搜索