在C++程序中读取XML文件

use*_*967 11 c++ xml

我正在尝试在我的C++程序中读取XML文件.XML文件看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<myprogram>
<configuration>
<window>
<height> 300 </height>
<width> 500 </width>
</window>
</configuration>
</myprogram>
Run Code Online (Sandbox Code Playgroud)

现在我可以查看XML文件并尝试按如下方式阅读:

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;
Run Code Online (Sandbox Code Playgroud)

一般来说,这似乎是个坏主意,它确实限制了XML文件的修改方式.上面的解决方案是非常手动的,如果XML中的任何内容发生变化,似乎必须更改整个读取方法.

有一个更好的方法吗?

Lih*_*ihO 5

您可以使用一些可以为您完成的库.如果您使用的是Windows平台,则可以使用MSXML,它已经是系统的一部分.

检查这个问题:在C++中读写XML文件

其他流行的库:, ,


pmr*_*pmr 5

您将需要一个 XML 解析器。那里有一堆:

我个人最喜欢的是 pugiXML,但这是个人喜好的问题。