XML 初級教程(二)

來源:互聯網
上載者:User

XML 初級教程(二)

作者:我本楚狂人

下載原始碼

一、SAX架構
SAX包含多個Handler處理器,其中有諸多函數以處理XML資源的時侯處理事件。
其中ContentHandler是最重要的,它用來對XML文檔進行解析,DTDHandler則對DTD檔案進行驗證。
當前MSXML3包含以下處理器:

  • IMXAttributes Interface
  • IMXWriter Interface
  • ISAXAttributes Interface
  • ISAXContentHandler Interface
  • ISAXDeclHandler Interface
  • ISAXDTDHandler Interface
  • ISAXEntityResolver Interface
  • ISAXErrorHandler Interface
  • ISAXLexicalHandler Interface
  • ISAXLocator Interface
  • ISAXXMLFilter Interface
  • ISAXXMLReader Interface

二、ISAXContentHandler介面
ContentHandler擁有以下函數:

characters endDocument startDocument endElement startElement
ignorableWhitespace startPrefixMapping processingInstruction skippedEntity  

今天要講解的函數是characters,startDocument/endDoucment,startElement/endElement函數,它們的用途:

三、函數講解

HRESULT characters(   [in] const wchar_t * pwchChars,   [in] int cchChars);   pwchChars擷取字串資訊。   cchChars擷取該字串長度。   
HRESULT startDocument();   該函數表明開始解析文檔。
HRESULT startElement(   [in] const wchar_t * pwchNamespaceUri,    [in] int cchNamespaceUri,    [in] const wchar_t * pwchLocalName,    [in] int cchLocalName   [in] const wchar_t *    [in] int cchQName);   [in] ISAXAttributes * pAttributes);    pwchNamespaceUri擷取命名空間URI。   cchNamespaceUri擷取URI的長度。   pwchLocalName擷取標記。   cchLocalName擷取標記長度。   pwchQName擷取QName。   cchQName擷取QName長度。   pAttributes擷取元素屬性資訊。      
  由於元素屬性並不固定,需要用如下方法擷取。   pAttributes->getLength(&l);   for ( int i=0; i<l; i++ ) {      wchar_t * ln, * vl; int lnl, vll;      pAttributes->getLocalName(i,&ln,&lnl);       prt(L" %s=", ln, lnl);      pAttributes->getValue(i,&vl,&vll);      prt(L"/"%s/"", vl, vll);   }

四、 使用ContentHandler:

HERO_XMLContentHandler* pHero_XML;ISAXXMLReaderPtr pReader = NULL;HRESULT hr;CHR(pReader.CreateInstance(__uuidof(SAXXMLReader))); //Only one content handler can be registered at a time.pHero_XML=HERO_XMLContentHandler::CreateInstance();//產生HERO_XMLContentHandler對象。CHR(pReader->putContentHandler(pHero_XML));//註冊HERO_XMLContentHandler處理器。CHR(pReader->parseURL(L"hero.xml"));//解析路徑。CHR(pReader->putContentHandler(NULL));


程式運行圖。

五、後記

希望本文能給大家協助,歡迎大家批評指正,具體請看原始碼。使用開發包為MSXML3,當然用Apache Xerces原理也是一樣的。 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.