我目前正在将一个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>
这个程序适合我。您使用的是最新版本的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