在这篇文章中,我将用.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 applicationint _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));
