在這篇文章中,我將用.NET框架來處理XML。
使用.NET中具備XML功能所帶來的優越性包括:
● 無需任何安裝、配置或重新分配,反正你的apps也是需要這個框架的,而只要你有這個框架,就萬事俱備了;
● 編碼更簡單,因為你不是在處理COM。比如,你不必要調用CoInitialize() 和 CoUninitialize();
● 具有比MSXML4更多的功能。
<?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>
#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; }
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));