Chinaunix首页 | 论坛 | 博客
  • 博客访问: 91391779
  • 博文数量: 19283
  • 博客积分: 9968
  • 博客等级: 上将
  • 技术积分: 196062
  • 用 户 组: 普通用户
  • 注册时间: 2007-02-07 14:28
文章分类

全部博文(19283)

文章存档

2011年(1)

2009年(125)

2008年(19094)

2007年(63)

分类: C/C++

2008-04-14 23:27:18

作者:Kate Gregory 来源:赛迪网 

在这篇文章中,我将用.NET框架来处理XML。

使用.NET中具备XML功能所带来的优越性包括:

● 无需任何安装、配置或重新分配,反正你的apps也是需要这个框架的,而只要你有这个框架,就万事俱备了;

● 编码更简单,因为你不是在处理COM。比如,你不必要调用CoInitialize() 和 CoUninitialize();

● 具有比MSXML4更多的功能。

XML实例

我将用下面的例子来加以说明:

 




用XmlDocument加载XML

处理XML的classes放在System::Xml namespace 中。XmlDocument表示一个DOM 文件,即XML被装载的子目录。这和在MSXML4方法中的DOMDocument是一样的。下面是一个简单的Managed C++应用程序,在内存中装入了XML文件:

#include "stdafx.h"
#using 
#include 
using namespace System;
#using 
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;iItem(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));

阅读(481) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~