在Managed C++中处理XML

2014-11-24 13:16:39 · 作者: · 浏览: 8
在这篇文章中,我将用.NET框架来处理XML。

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

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

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

● 具有比MSXML4更多的功能。

XML实例


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

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










         


用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));