c++ - 需要一个非常简单的示例,用于用 C 或 C++ 解析和编写 XML 文档

标签 c++ c xml

我从事 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/

相关文章:

c++ - 如何为 QTreeView 中的特定行创建自定义 QItemDelegate?

C++ 无法从 main.cpp 中的另一个文件实例化类

c - 在c中写入一个2位int,仅包含<unistd.h>

c++ - 对大文件的可移植支持

python - HTML 清理代码不太有效

c# - 如何在 C# XML 文档中标记代码

c++ - 这段代码是什么意思?

c++ - 我如何检查mysql用户是否具有root用户的权限

c - 对数组的引用与对数组指针的引用

c# - 用于 C# 解析的 XML 模式的 "ref"属性