使用xerces-c生成XML并输出

这篇博客介绍了如何使用xerces-c库生成XML文档,并将其输出到屏幕。作者分享了遇到的困难,如找到适当的输出示例,编译时的链接问题以及C++语法不熟悉导致的错误。最终,通过DOMImplementation和StdOutFormatTarget实现了XML的创建和显示。尽管过程中遇到了一些警告,但博主认为这为简单的XML操作提供了一个参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天试用了xerces-c , 我觉得果然好像还是不如Java版本的XML api好用。当然是个人愚见。对于创建XML实例还是比较简单的,而要输出到屏幕则着实费了一番脑筋。在baidu、google上都难以找到实例。后来 我想到它的samples中有类似的例子,就下载源码来研究。最后做了一个非常简单的版本。代码如下:
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/framework/StdOutFormatTarget.hpp>
#include <iostream>
using namespace xercesc;

int main(int argc, char* argv[])
{
try {
XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch) {
// Do your failure processing here
return 1;
}
XMLCh str[10];
// Do your actual work with Xerces-C++ here.
XMLString::transcode("Core", str, 9);
DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(str);//DOMImplementation::getImplementation();
XMLString::transcode("Test", str, 9);
DOMDocument*        doc = impl->createDocument(0, str, 0);
XMLString::transcode("Child", str, 9);
DOMElement*         node = doc->createElement(str);
DOMElement*         root = doc->getDocumentElement();
root->appendChild(node);
DOMLSOutput* output = ((DOMImplementationLS*)impl)->createLSOutput();
DOMLSSerializer*  serial = ((DOMImplementationLS*)impl)->createLSSerializer();
output->setByteStream( new StdOutFormatTarget());
serial->write(doc, output);
doc->release();
serial->release();
delete impl;
delete str;

XMLPlatformUtils::Terminate();

// Other terminations and cleanup.
return 0;
}
要得到 DOMImplementation,DOMImplementationRegistry::getDOMImplementation(str);和 DOMImplementation::getImplementation();的效果是一样的。我开始使用的后一种,但是由于C++不熟练,后边有地 方弄错了,编译不通过。后来根据samples改为前一种了。使用StdOutFormatTarget可以将结果输出到屏幕上。
编译时我使用的静态链接到他的xerces-c_static_3.lib上的,然后还需要添加advapi32.lib,因为它进行transcode的时候好像用到了注册表相关的方法(否则编译不通过)。
即时编译通过了,也有很多warning,如:
Test.obj : warning LNK4217: 本地定义的符号 ??3XMemory@xercesc_3_0@@SAXPAX@Z (public: static void __cdecl xercesc_3_0::XM emory::operator delete(void *)) 在函数 __unwindfunclet$_main$2 中导入

这点我就不明白了。另外,有的object使用完需要release,这个方法又不是每个类都有,也比较麻烦,有时候不知道什么需要。当然我现在只是玩玩而已。

实现简单,留作参考。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值