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

Bha*_*ava 0 c++ xml unix libxml2

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

在此先感谢Bhargava

Ale*_*min 7

由于这是标记的C++,我假设您可以使用libxml ++库绑定.

我写了一个简单的程序:

  • 使用a解析文档 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;
}
Run Code Online (Sandbox Code Playgroud)

鉴于此输入:

<!-- file.xml -->
<root>
  <a>
    <b attr="I want to get this"> </b>
  </a>
</root>
Run Code Online (Sandbox Code Playgroud)

代码将输出:

I want to get this
Run Code Online (Sandbox Code Playgroud)

要在Unix系统上编译它:

c++ `pkg-config libxml++-2.6 --cflags` `pkg-config libxml++-2.6 --libs` file.cpp
Run Code Online (Sandbox Code Playgroud)