1

我目前正在将 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>
4

1 回答 1

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
于 2014-07-30T11:37:21.620 回答