我正在尝试在我的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中的任何内容发生变化,似乎必须更改整个读取方法.
有一个更好的方法吗?