在C ++程序中读取XML文件 [英] reading an XML file in a C++ program
问题描述
我想在我的C ++程序中读取一个XML文件。 XML文件看起来像这样:
<?xml version =1.0encoding =utf-8? ;
< myprogram>
< configuration>
< window>
< height> 300< / height>
< width> 500< / width>
< / window>
< / configuration>
< / myprogram>现在我可以看看XML文件,并尝试这样读:
ifstream in(mydata.xml);
//忽略<?xml行
in.ignore(200,'\\\
');
//我知道我想要的第一个值是窗口高度,所以我可以忽略< myprogram> < configuration>和< window>
// ignore< myprogram>
in.ignore(200,'\\\
');
// ignore< configuration>
in.ignore(200,'\\\
');
// ignore< window>
in.ignore(200,'\\\
');
string s; int height;
//好吧,现在我有我的身高
在>> s>>高度;
一般来说,这似乎是一个坏主意,它真的限制了如何修改XML文件。上面的解决方案是非常手动的,如果XML中的任何东西改变,似乎整个阅读它的方法必须改变。
有更好的方法这个?
解决方案你可以使用一些库来为你做。如果您使用的是Windows平台,则可以使用 MSXML 。
检查此问题:在C ++中读取XML文件
其他常用库: xerces , tinyxml , rapidxml
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: xerces, tinyxml, rapidxml
这篇关于在C ++程序中读取XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!