程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 在Managed C++中處理XML

在Managed C++中處理XML

編輯:C++入門知識

在這篇文章中,我將用.NET框架來處理XML。

使用.NET中具備XML功能所帶來的優越性包括:

● 無需任何安裝、配置或重新分配,反正你的apps也是需要這個框架的,而只要你有這個框架,就萬事俱備了;

● 編碼更簡單,因為你不是在處理COM。比如,你不必要調用CoInitialize() 和 CoUninitialize();

● 具有比MSXML4更多的功能。

XML實例


我將用下面的例子來加以說明:

<?xml version="1.0" encoding="utf-8" ?> 

<PurchaseOrder>

<Customer id="123"/>

<Item SKU="1234" Price="4.56" Quantity="1"/>

<Item SKU="1235" Price="4.58" Quantity="2"/>

</PurchaseOrder>


用XmlDocument加載XML

處理XML的classes放在System::Xml namespace 中。XmlDocument表示一個DOM 文件,即XML被裝載的子目錄。這和在MSXML4方法中的DOMDocument是一樣的。下面是一個簡單的Managed C++應用程序,在內存中裝入了XML文件:

#include "stdafx.h"

#using <mscorlib.dll>

#include <tchar.h>

using namespace System;

#using <System.Xml.dll>

using namespace System::Xml;

// This is the entry point for this application

int _tmain(void)

{

  XmlDocument* xmlDoc = new XmlDocument();

  try

  {

    xmlDoc->Load("sample.xml");

    System::Console::WriteLine("Document loaded ok." );

  }

  catch (Exception *e)

  {

    System::Console::WriteLine("load problem");

    System::Console::WriteLine(e->Message);

  }

  return 0;

}


#using 語句非常重要。沒有它,就會出現一些奇怪的編譯錯誤,如Xml : is not a member of System 或 Xml : a namespace with this name does not exist. 在C#或VB.NET中,有一個Project,Add References 菜單項目自動為你完成這項工作,但是在C++中,編程者必須自己去完成。你可以在在線幫助中找到class或namespace匯編。

另外注意到,在編碼中沒有象COM方法中那樣使用Load()返回值。如果不能加載XML,加載程序將報告異常。

文檔內容的簡單算法

這裡是.NET方式中相應的編碼。

xmlDoc->Load("sample.xml");

double total = 0;

System::Console::WriteLine("Document loaded ok." );

XmlNodeList* items = xmlDoc->GetElementsByTagName("Item");

long numitems = items->Count;

for (int i=0;i<numitems;i++)

{

  XmlNode* item = items->Item(i);

  double price =

    Double::Parse(item->Attributes->GetNamedItem("Price")->

                  get_Value());

  double qty =

    Double::Parse(item->Attributes->GetNamedItem("Quantity")->

                  get_Value());

  total += price * qty;

}

System::Console::WriteLine("Purchase Order total is ${0}",

                           __box(total));

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved