Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

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

//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, '
');

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...