【问题标题】:XPath query does not work with pugixmlXPath 查询不适用于 pugixml
【发布时间】:2014-07-30 10:07:04
【问题描述】:

我目前正在将 C++ 项目从 libxml2 移植到 pugixml。我有一个 XPath 查询,它曾经与 libxml2 完美配合,但使用 pugixml 返回零节点:

"//*[local-name(.) = '" + name + "']"

其中name 是我要检索的元素的名称。任何人都可以了解正在发生的事情吗?

代码:

const string path = "//*[local-name(.) = '" + name + "']";
std::cerr << path << std::endl;
try {
   const xpath_node_set nodes = this->doc.select_nodes(path.c_str());
   return nodes;
} catch(const xpath_exception& e) {
   std::cerr << e.what() << std::endl;
   throw logic_error("Could not select elements from document.");
}

姓名: “页面”

XML:

<MyDocument>
  <Pages>
    <Page>
      <Para>
        <Word>Some</Word>
        <Word>People</Word>
      </Para>
    </Page>
    <Page>
      <Para>
        <Word>Some</Word>
        <Word>Other</Word>
        <Word>People</Word>
      </Para>
    </Page>
  </Pages>
</MyDocument>

【问题讨论】:

  • 好吧,您需要发布示例以允许其他人重现问题,因此我们需要查看最小的 XML 示例输入和宿主语言中代码的最小 sn-p,而不知道 @987654325 @ 是以及您的输入看起来如何,我们只能假设路径没有选择您处理的样本中的任何内容。

标签: xml c++11 xpath libxml2 pugixml


【解决方案1】:

这个程序适合我。你用的是最新版的pugixml吗?

另外,我确实注意到 pugixml 不适用于命名空间,您可能需要在要搜索的节点名称中指定它们。

我刚刚检查过,它适用于命名空间。

#include <pugixml.hpp>

#include <iostream>

const char* xml =
"<MyDocument>"
"  <Pages>"
"    <Page>"
"      <Para>"
"        <Word>Some</Word>"
"        <Word>People</Word>"
"      </Para>"
"    </Page>"
"    <Page>"
"      <Para>"
"        <Word>Some</Word>"
"        <Word>Other</Word>"
"        <Word>People</Word>"
"      </Para>"
"    </Page>"
"  </Pages>"
"</MyDocument>";

int main()
{
    std::string name = "Para";

    const std::string path = "//*[local-name(.) = '" + name + "']";

    pugi::xml_parse_result result;

    pugi::xml_document doc;

    doc.load(xml);

    const pugi::xpath_node_set nodes = doc.select_nodes(path.c_str());

    for(auto& node: nodes)
    {
        std::cout << node.node().name() << '\n';
    }
}

输出

Para
Para

【讨论】:

    猜你喜欢
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多