使用 libxml2 解析 xml 文件时 UNIX 中的 C++

标签 c++ xml unix libxml2

如何使用 xpath 使用 libxml2 在 C++ 中从 xml 文件中检索节点和属性值?

提前致谢, 巴尔加瓦

最佳答案

由于这是标记为 C++,我假设您可以使用 libxml++ 库绑定(bind)。

我写了一个简单的程序:

  • 使用 DomParser 解析文档
  • 在文档根节点上使用 find() 进行 XPath 查询以获取属性。
  • 将 XPath 结果的第一个节点转换为 Attribute 节点
  • 使用 get_value() 获取该属性字符串值
  • 显示该值

代码如下:

#include <iostream>
#include <libxml++/libxml++.h>

using namespace std;
using namespace Glib;
using namespace xmlpp;

int main(int argc, char* argv[])
{
    // Parse the file
    DomParser parser;
    parser.parse_file("file.xml");
    Node* rootNode = parser.get_document()->get_root_node();

    // Xpath query
    NodeSet result = rootNode->find("/root/a/b/@attr");

    // Get first node from result
    Node *firstNodeInResult = result.at(0);
    // Cast to Attribute node (dynamic_cast on reference can throw [fail fast])
    Attribute &attribute = dynamic_cast<Attribute&>(*firstNodeInResult);

    // Get value of the attribute
    ustring attributeValue = attribute.get_value();

    // Print attribute value
    cout << attributeValue << endl;
}

鉴于此输入:

<!-- file.xml -->
<root>
  <a>
    <b attr="I want to get this"> </b>
  </a>
</root>

代码将输出:

I want to get this

在 Unix 系统上编译:

c++ `pkg-config libxml++-2.6 --cflags` `pkg-config libxml++-2.6 --libs` file.cpp

关于使用 libxml2 解析 xml 文件时 UNIX 中的 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4176985/

相关文章:

c++ - 是否可以在 C++ 的 Mutator 中使用 Mutator?

c++ - 在 Lua 5.2 中使用 'module' 函数?

java - 如何将 XML 文件以字符串形式放入 Java 文件中

bash - shell脚本中的性能问题

c - fork的共享内存

c++ - 从标准输入中捕获字符,而无需等待按下回车键

c++ - 接受带有两个交换字母的输入的函数?

xml - 如何计算 XQuery 中不同值的每个实例?

javascript - Microsoft.XMLDOM js 问题

linux - 在 SVN 更新后做一些事情