首頁  >  文章  >  後端開發  >  實例簡析XPath串函數和XSLT

實例簡析XPath串函數和XSLT

黄舟
黄舟原創
2017-03-01 16:53:372012瀏覽

XPath(xml Path language)是一種處理XML文檔段的語言。 XSLT(Extensible Stylesheet Language Transformations,可擴充樣式表語言轉換)使用XPath描述表達式和位址路徑控制節點選取。 XSLT可以將XML轉換為各種格式,如HTML或其他格式。 
    以下用一個郵件合併程序簡單說明XPath的字串函數。下面的XML檔案中包含數據,XSLT檔案中包含對郵件格式的定義。 MSXML4.0對XML文件套用樣式表,產生一個合併的郵件文字文件。
XML檔Letter.xml



  July 17, 2002
  
     Vicky
     P
     Male
  
  
900 National Pkwy Suite 105 Bellevue WA 98007 USA
ESTATE OF JOHN DOE / FILE NO. 12345.6789 Please pay the PRoperty taxes as soon as possible. John M Sr. Tax Consultant

XSLT樣式表文件Letter.xsl







   
   
To,










Regarding: 

Dear Mr. Miss 
,



Sincerely,





上面的樣式表舉例說明了concat和starts-with XPath字串函數和怎樣在輸出文字中增加新行,還有定義和使用變數。
    以下是程式的執行結果。

1.VC6建立Win32控制台應用程式。
2.在stdafx.h中加入下面的程式碼:

#include 
#include 
#include 
#import "msxml4.dll"
// If this import statement fails, you need to install MSXML 4.0 SP1 from:
//http://msdn.microsoft.com/downloads/sample.asp?url=/MSDN-FILES/027/001/766/msdncompositedoc.xml
#include 
// If this include statement fails, you need to install MSXML 4.0 SP1 SDK from:
//http://msdn.microsoft.com/downloads/sample.asp?url=/MSDN-FILES/027/001/766/msdncompositedoc.xml
// You also need to add the include file and library search path
// to Visual C++'s list of directories (Tools > Options... > Directories).
using namespace MSXML2;
inline void EVAL_HR( HRESULT _hr ) 
   { if FAILED(_hr) throw(_hr); }
#define TEMP_SIZE  _MAX_PATH               // size of short buffer
static _TCHAR   szTemp[TEMP_SIZE];         // multipurpose buffer on stack
static DWord    dwLen;

3.上面的程式碼引入MSXML4類型庫,包含MSXML頭文件,檢查HRESULT值並聲明了一些全域變數。
4.main函數:

  int main(int argc, char* argv[])
{
 try
 {
  EVAL_HR(CoInitialize(NULL));
  // Make sure that MSXML 4.0 is installed
  if (!isMSXMLInstalled())
   return -1;
  // Make sure that XML and XSL file names are passed
  // as command line parameters
  if (argc < 3)
   // Show proper message here
   return -1;
  
  IXMLDOMDocument2Ptr pXMLDoc = NULL;
  IXMLDOMDocument2Ptr pXSLDoc = NULL;
  
  // Load the XML document
  if (loadDocument(pXMLDoc, argv[1], true))
  {
   // Load the stylesheet
   if (loadDocument(pXSLDoc, argv[2], false))
   {
    _ftprintf(stdout, pXMLDoc->transformNode(pXSLDoc));
   }
   else
   {
    printMSXMLError(pXSLDoc);
   }
  }
  else
  {
   printMSXMLError(pXMLDoc);
  }
 }
 catch(...)
 {//exception handling
 }
 
 _ftprintf(stdout, "\n\nPress Enter to continue...");
 getchar();
 CoUninitialize();
 return 0;
}

5.XML檔案和XSLT樣式表檔案名稱作為命令列參數傳遞給應用程式。主函數透過呼叫isMSXMLInstalled驗證    MSXML4.0是否安裝。接下來兩次呼叫loadDocument;先是載入XML文檔,然後是載入XSLT樣式表。 最後呼叫transformNode進行轉換。

6.本範例程式碼下載:http://www.perfectxml.com/CPPMSXML/downloads/20020716MailMerge.zip

# 以上就是實例簡單化XPath字串函數和XSLT的內容,更多相關內容請關注PHP中文網(www.php.cn)!


#
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn