简体   繁体   中英

reading an XML file in a C++ program

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?

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: , ,

You will need a XML Parser. There are a bunch out there:

My personal favorite is pugiXML but that is a question of personal preference.

您可以使用具有解析XML功能的POCO库

boost属性树适用于xml,我会用它。

In multi-platform source I usually use Qt XML reader.

You have 3 ways to read:

  1. Qt core QXmlStreamReader - Qt way of XML reading
  2. SAX2 reader - standard SAX2 reader with content handling class
  3. DOM reader - DOM document reader with XML nodes

If you write Windows only software, you should use MSXML 6. Since Windows XP SP3 MSXML 6.0 is part of the OS.

On Linux you should use libxml2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM