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