Read Write XML File In C++ [closed]

2020-02-05 04:50发布

I researched a lot on how to read and write ( update ) a simple .xml file in C++ but i am not able to develop the code for it.

I work and installed xerces-c library that I think is needed to use DOM or SAX2 parser to read it.

Please someone can help to write the code for it.

A sample code to do this will be quite helpful.

Thanks & best Regards, Adarsh Sharma

标签: c++ xml xerces-c
2条回答
The star\"
2楼-- · 2020-02-05 05:15

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.

查看更多
你好瞎i
3楼-- · 2020-02-05 05:31

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

查看更多
登录 后发表回答