gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:58:06 24 4
gpt4 key购买 nike

如何使用 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/

24 4 0
文章推荐: c++ - 两个头文件可以包含 C++ 中命名相同的类吗?
文章推荐: php - 我的表 sql 中缺少一列
文章推荐: javascript - 向下拖动时 Div mask Textarea 内容
文章推荐: javascript - 使用 ng-repeat 时在