在 C++ 程序中读取 XML 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9473235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reading an XML file in a C++ program
提问by user974967
I'm trying to read an XML file in my C++ program. The XML file looks something like this:
我正在尝试在我的 C++ 程序中读取 XML 文件。XML 文件如下所示:
<?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:
现在我可以查看 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;
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.
一般来说,这似乎是一个坏主意,它确实限制了 XML 文件的修改方式。上面的解决方案是非常手动的,如果 XML 中的任何内容发生变化,似乎整个读取它的方法都必须更改。
Is there a better way to do this?
有一个更好的方法吗?
采纳答案by LihO
You could use some library that will do it for you. If you are working on Windows platform, you could use MSXMLwhich is part of the system already.
您可以使用一些可以为您完成的库。如果你在 Windows 平台上工作,你可以使用MSXML,它已经是系统的一部分。
Check this question: Read Write XML File In C++
检查这个问题:Read Write XML File In C++
回答by pmr
回答by 01100110
boost property tree works very well with xml, I would use that.
boost 属性树与 xml 配合得很好,我会使用它。
回答by Naszta
In multi-platform source I usually use Qt XML reader.
在多平台源中,我通常使用 Qt XML 阅读器。
You have 3 ways to read:
你有3种阅读方式:
- Qt core QXmlStreamReader- Qt way of XML reading
- SAX2 reader- standard SAX2 reader with content handlingclass
- DOM reader- DOM document reader with XML nodes
- Qt 核心 QXmlStreamReader- Qt 读取 XML 的方式
- SAX2 阅读器- 具有内容处理类的标准 SAX2 阅读器
- DOM reader- 带有 XML 节点的 DOM 文档阅读器
If you write Windows only software, you should use MSXML 6. Since Windows XP SP3 MSXML 6.0is part of the OS.
如果您只编写 Windows 软件,则应使用 MSXML 6。因为 Windows XP SP3 MSXML 6.0是操作系统的一部分。
On Linux you should use libxml2.
在 Linux 上,您应该使用libxml2。
回答by Roman Smelyansky
You can use POCO library which has functions for parsing XML
您可以使用具有解析 XML 功能的 POCO 库