Read Write XML File In C++

Adarsh Sharma picture Adarsh Sharma · Mar 24, 2011 · Viewed 74.8k times · Source

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

Answer

LihO picture LihO · Jan 25, 2012

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