导航

Xerces C++简介

Posted on 2007-01-18 15:27  lirengang  阅读(1824)  评论(0)    收藏  举报

1.使用

为了使用Xerces,必须在初始化时调用:

XMLPlatformUtils::Initialize();

最后调用:

XMLPlatformUtils::Terminate();

 

一般说明:

由于XML使用编码集的原因,在Xerces中引入了XMLCh这种数据类型(具体怎么表示????),如果想显示之,可以如下:

XMLCh* pxml;

char* psz = XMLString::transcode( pxml );

cout << psz;

XMLString::release( &psz );         // 这里不能少,否则会内存泄露

为了避免内存泄露,也可以通过包装类的方式来做,如下:

class StrX

{

public :

    StrX(const XMLCh* const toTranscode) {

        fLocalForm = XMLString::transcode(toTranscode);

    }

    ~StrX() {

        XMLString::release(&fLocalForm);

    }

    const char* localForm() const {

        return fLocalForm;

    }

private :

    char*   fLocalForm;

};

 

// 同时增加该包装的流输出接口:

inline ostream& operator<<(ostream& target, const StrX& toDump) {

    target << toDump.localForm();

    return target;

}

1.1 使用DOM

一个简单的例子:

// 获得DOMParser

static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };

DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);

DOMBuilder        *parser = ( ( DOMImplementationLS* )impl )->createDOMBuilder ( DOMImplementationLS::MODE_SYNCHRONOUS, 0);

 

/*

另一种获得Parser的方法:

DOMParser* parser = new DOMParser();          // 新建对象

parser->setDoNamespaces( true );                            // 设置属性

parser->parse( "c:\\out.xml" );                           // 解析

DOMDocument* doc = parser->getDocument(); // 获得DOM文档

 

 

delete parser;                                                   // 由于它不再是由Builder管理的对象,必须delete

*/

 

// 解析XML文件

DOMDocument* doc = parser->parseURI( "c:\\x.xml" );

 

// 通过DOM操纵XML文件

// 获得XML文件根节点

DOMNode* root = doc->getDocumentElement();

 

 

// 最后要释放DOM Parser

parser->release();

1.1.1 一些常用类和方法、属性等

DOMNode:结点

bool hasAttributes();      // 是否有属性

DOMNamedNodeMap* getAttributes();          // 获得属性列表

XMLCh* getNodeName();                  // 结点名

XMLCh* getNodeValue();                   // 结点值

DOMNode* getFirstChild();                  // 获得第一个子结点,如果不存在则返回NULL

DOMNode* getNextSibling();        // 获得下一个子结点,如果不存在则返回NULL

NodeType getNodeType();                  // 结点类型

    enum NodeType {

        ELEMENT_NODE                = 1,

        ATTRIBUTE_NODE              = 2,

        TEXT_NODE                   = 3,

        CDATA_SECTION_NODE          = 4,

        ENTITY_REFERENCE_NODE       = 5,

        ENTITY_NODE                 = 6,

        PROCESSING_INSTRUCTION_NODE = 7,

        COMMENT_NODE                = 8,

        DOCUMENT_NODE               = 9,

        DOCUMENT_TYPE_NODE          = 10,

        DOCUMENT_FRAGMENT_NODE      = 11,

        NOTATION_NODE               = 12

    };

常见判断:if( n->getNodeType() == DOMNode::ELEMENT_NODE )

////////// 常用的一种枚举结点的方法:

for(DOMNode* child=root->getFirstChild();child!=NULL;child=child->getNextSibling())

 

DOMNamedNodeMap:属性列表

int getLength();             // 属性长度

DOMAttr* item(int i);     // 获得第i个属性

 

DOMAttr:属性

XMLCh* getName();     // 获得属性名

XMLCh* getValue();      // 获得属性值

 

1.2 使用SAX

SAX是一种基于Event的编程模型,处理方式与DOM完全不一样。

一个例子:

// 使用SAX必须通过一个Handler来进行XML解析,它从HandleBaseXMLFormatTarget继承,通过在适当接口中编写事件处理代码实现基于EventXML解析。如下:

class SAXPrintHandlers : public HandlerBase, private XMLFormatTarget {

    // -----------------------------------------------------------------------

    // Constructors

    // -----------------------------------------------------------------------

    SAXPrintHandlers (

        const   char* const                 encodingName

        , const XMLFormatter::UnRepFlags    unRepFlags

   );

    ~SAXPrintHandlers();

    // -----------------------------------------------------------------------

    // Implementations of the format target interface

    // -----------------------------------------------------------------------

    void writeChars (

        const   XMLByte* const toWrite

    );

    void writeChars (

        const   XMLByte* const toWrite

        , const unsigned int    count

        , XMLFormatter* const   formatter

    );

    // -----------------------------------------------------------------------

    // Implementations of the SAX DocumentHandler interface

    // -----------------------------------------------------------------------

    void endDocument();

    void endElement(const XMLCh* const name);

    void characters(const XMLCh* const chars, const unsigned int length);

    void ignorableWhitespace (

        const   XMLCh* const    chars

        , const unsigned int    length

    );

    void processingInstruction (

        const   XMLCh* const    target

        , const XMLCh* const    data

    );

    void startDocument();

    void startElement(const XMLCh* const name, AttributeList& attributes);

    // -----------------------------------------------------------------------

    // Implementations of the SAX ErrorHandler interface

    // -----------------------------------------------------------------------

    void warning(const SAXParseException& exception);

    void error(const SAXParseException& exception);

    void fatalError(const SAXParseException& exception);

    // -----------------------------------------------------------------------

    // Implementation of the SAX DTDHandler interface

    // -----------------------------------------------------------------------

    void notationDecl (

        const   XMLCh* const    name

        , const XMLCh* const    publicId

        , const XMLCh* const    systemId

    );

    void unparsedEntityDecl (

        const   XMLCh* const    name

        , const XMLCh* const    publicId

        , const XMLCh* const    systemId

        , const XMLCh* const    notationName

    );

}

 

在主程序中:

static const char* encodingName = "UTF-8";             // 编码集

static XMLFormatter::UnRepFlags unRepFlags = XMLFormatter::UnRep_CharRef;

 

SAXParser* parser = new SAXParser;        // 新建SAX对象

SAXPrintHandlers handler(encodingName, unRepFlags);    // 新建Handler对象

parser->setDocumentHandler(&handler);                          // 设置Handler处理对象

parser->parse(xmlFile);                                                   // 解析

delete parser;

 

具体的使用SAX的方法如何????(需要了解Handler接口方法的含义)

...........