欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Xerces-c DOM XML文件的构造

程序员文章站 2022-06-17 14:13:33
...

Xerces中构造xml很简单,但是想输出就很麻烦,Xerces支持三种输出 输出到内存
输出到标准输出 输出到本地文件
下面列出用到的一些重要的类,可以查询官网API解锁更多的用法

1.DOMImplementation和DOMImplementationLS这两货是DOM界的造物者,如果你发现你有构造不了的类,查询这两货的API就可以啦,比如
DOMDoument DOMLSSerializer
2.DOMLSOutput获得输出的句柄,通过与输出目标绑定 正如上面提及的 MemBufFormatTarget StdOutFormatTarget LocalFileFormatTarget,此外还可以设置输出的编码方式等行为
3.DOMLSSerializer 串行化DOMDocument句柄和输出句柄,使得二者相关联

下面来看看例子吧,解锁它的用法

#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/dom/DOM.hpp>
#include <iostream>
#include <xercesc/framework/LocalFileFormatTarget.hpp>

#define Transcode_1(x)  XMLString::transcode(x)
#define Transcode_3(x,y,z) XMLString::transcode(x,y,z)

using namespace xercesc;

int main()
{
    try 
    {
        XMLPlatformUtils::Initialize();
    }
    catch (const XMLException& toCatch)
    {
        std::cerr << Transcode_1(toCatch.getMessage());
    }
    try 
    {
        DOMImplementation* imp = DOMImplementationRegistry::getDOMImplementation(Transcode_1("Core"));
        DOMDocument* doc = imp->createDocument(0,Transcode_1("root"),0);

        DOMElement* node = doc->createElement(Transcode_1("node1"));
        node->setAttribute(Transcode_1("name"),Transcode_1("node1"));
        node->setTextContent(Transcode_1("node1"));

        DOMElement* root = doc->getDocumentElement();
        root->appendChild(node);

        DOMElement* node2 = doc->createElement(Transcode_1("node2"));
        node2->setAttribute(Transcode_1("name"),Transcode_1("node2"));
        node2->setTextContent(Transcode_1("node2"));

        root->appendChild(node2);

        DOMElement* node2_1 = doc->createElement(Transcode_1("node2_1"));
        node2_1->setAttribute(Transcode_1("name"),Transcode_1("node2_1"));
        node2_1->setTextContent(Transcode_1("node2_1"));
        node2->appendChild(node2_1);

        DOMLSOutput* output = dynamic_cast<DOMImplementationLS*>(imp)->createLSOutput();
        DOMLSSerializer* serial = dynamic_cast<DOMImplementationLS*>(imp)->createLSSerializer();
        XMLFormatTarget* target = new LocalFileFormatTarget("2.xml");
        output->setByteStream(target);
        serial->write(doc,output);
        doc->release();
        serial->release();
        delete target;
    }
    catch (const DOMException& toCatch)
    {
        std::cerr << Transcode_1(toCatch.getMessage());
    }
    return 0;
}
相关标签: XML Xerces c++