我从事 C 项目,需要实现一些与 XML 文件的交互。
我需要一个非常简单示例来解析和编写 XML 文件。
我确实更喜欢小型库(例如一个 .h 文件和一个 .c 文件),而不是需要安装的库
如果有人可以向我展示,我会非常高兴:
- 如何解析以下示例中的数据
- 如何生成以下示例中的数据
XML 数据:
<root>
<source name = 'source1' isReadOnly = 'false'>
<view name = 'view1' />
<view name = 'view2' />
</source>
<source name = 'source2' isReadOnly = 'true'>
<view name = 'view1' />
<view name = 'view2' />
</source>
</root>
最佳答案
我发现 pugixml 非常容易使用。它是一个小的源文件,您可以将其编译到您的项目中。
示例C++03:
#include <fstream>
#include <iostream>
#include "pugixml.hpp"
int main()
{
using namespace pugi;
// Load XML file from fstream
std::ifstream xml_file("test.xml");
if(!xml_file)
{
std::cerr << "ERROR: opening XML file: " << std::endl;
return 1;
}
xml_document doc;
xml_parse_result res = doc.load(xml_file);
if(!res)
{
std::cerr << "ERROR: " << res.description() << std::endl;
return 1;
}
// get all children of <root><source>
xml_object_range<xml_named_node_iterator> sources =
doc.child("root").children("source");
// Iterate through <root><source> children
xml_named_node_iterator s;
for(s = sources.begin(); s != sources.end(); ++s)
{
// get all children named <root><source><view>
xml_object_range<xml_named_node_iterator> views =
s->children("view");
// Iterate through <root><source><view> children
xml_named_node_iterator v;
for(v = views.begin(); v != views.end(); ++v)
std::cout << v->attribute("name").value() << '\n';
}
}
示例C++11:
#include <fstream>
#include <iostream>
#include "pugixml.hpp"
int main()
{
using namespace pugi;
std::ifstream xml_file("test.xml");
if(!xml_file)
{
std::cerr << "ERROR: opening XML file: " << std::endl;
return 1;
}
xml_document doc;
xml_parse_result res = doc.load(xml_file);
if(!res)
{
std::cerr << "ERROR: " << res.description() << std::endl;
return 1;
}
auto sources = doc.child("root").children("source");
for(auto&& s: sources)
{
auto views = s.children("view");
for(auto&& v: views)
std::cout << v.attribute("name").value() << '\n';
}
}
关于c++ - 需要一个非常简单的示例,用于用 C 或 C++ 解析和编写 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26700020/