Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading an XML file in a C++ program

Tags:

c++

xml

I'm trying to read an XML file in my C++ program. The XML file looks something like this:

<?xml version="1.0" encoding="utf-8"?>
<myprogram>
<configuration>
<window>
<height> 300 </height>
<width> 500 </width>
</window>
</configuration>
</myprogram>

Right now I can look at the XML file and try to read it like this:

ifstream in("mydata.xml");

//ignore the <?xml line
in.ignore(200, '\n');

//i know that the first value i want is the window height so i can ignore <myprogram> <configuration> and <window>

//ignore <myprogram>
in.ignore(200, '\n');

//ignore <configuration>
in.ignore(200, '\n');

//ignore <window>
in.ignore(200, '\n');

string s; int height;

//okay, now i have my height
in >> s >> height;

In general this seems like a bad idea and it really limits how the XML file can be modified. The above solution is very manual and if anything in the XML changes it seems that the entire method of reading it would have to be changed.

Is there a better way to do this?

like image 293
user974967 Avatar asked Feb 27 '12 22:02

user974967


People also ask

How do I read XML files?

If all you need to do is view the data in an XML file, you're in luck. Just about every browser can open an XML file. In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome".

What is XML parser in C?

The Oracle XML parser for C reads an XML document and uses DOM or SAX APIs to provide programmatic access to its content and structure. You can use the parser in validating or nonvalidating mode. This chapter assumes that you are familiar with the following technologies: Document Object Model (DOM).

What is the best way to read XML in C #?

C# Program to Read and Parse an XML File Using XmlReader Class. The XmlReader class in C# provides an efficient way to access XML data. XmlReader. Read() method reads the first node of the XML file and then reads the whole file using a while loop.


1 Answers

You could use some library that will do it for you. If you are working on Windows platform, you could use MSXML which is part of the system already.

Check this question: Read Write XML File In C++

Other popular libraries: xerces, tinyxml, rapidxml

like image 86
LihO Avatar answered Oct 12 '22 07:10

LihO