Read Write XML File In C++ [closed]

不羁的心 提交于 2019-11-28 09:20:20
LihO

I recommend MSXML. It may look complicated, but it's nice and easy when you get used to it.
Here's a sample:

input.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Car>
    <Wheels>
        <Wheel1>FL</Wheel1>
        <Wheel2>FR</Wheel2>
        <Wheel3>RL</Wheel3>
        <Wheel4>RR</Wheel4>
    </Wheels>
</Car>

code:

#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#import <msxml6.dll> rename_namespace(_T("MSXML"))

int main(int argc, char* argv[]) {
    HRESULT hr = CoInitialize(NULL); 
    if (SUCCEEDED(hr)) {
        try {
            MSXML::IXMLDOMDocument2Ptr xmlDoc;
            hr = xmlDoc.CreateInstance(__uuidof(MSXML::DOMDocument60),
                                       NULL, CLSCTX_INPROC_SERVER);
            // TODO: if (FAILED(hr))...

            if (xmlDoc->load(_T("input.xml")) != VARIANT_TRUE) {
                printf("Unable to load input.xml\n");
            } else {
                printf("XML was successfully loaded\n");

                xmlDoc->setProperty("SelectionLanguage", "XPath");
                MSXML::IXMLDOMNodeListPtr wheels = xmlDoc->selectNodes("/Car/Wheels/*");
                printf("Car has %u wheels\n", wheels->Getlength());

                MSXML::IXMLDOMNodePtr node;
                node = xmlDoc->createNode(MSXML::NODE_ELEMENT, _T("Engine"), _T(""));
                node->text = _T("Engine 1.0");
                xmlDoc->documentElement->appendChild(node);
                hr = xmlDoc->save(_T("output.xml"));
                if (SUCCEEDED(hr))
                    printf("output.xml successfully saved\n");
            }
        } catch (_com_error &e) {
            printf("ERROR: %ws\n", e.ErrorMessage());
        }
        CoUninitialize();
    }
    return 0;
}

output: XML was successfully loaded Car has 4 wheels output.xml successfully saved

output.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Car>
    <Wheels>
        <WheelLF>1</WheelLF>
        <WheelRF>2</WheelRF>
        <WheelLR>3</WheelLR>
        <WheelRR>4</WheelRR>
    </Wheels>
    <Engine>Engine 1.0</Engine></Car>

You will find everything you need here:
http://msdn.microsoft.com/en-us/library/ms765540(v=vs.85).aspx

Hope someone finds this useful ;)

Boost serializer can do the trick, if you pass an object to it, it write a file (binary or xml or even a simple text file) with all the class properties.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!