无法使用 <script> XPath 表达式通过 libxml++ 获取 XHTML 内容
can't get xhtml <script> content with libxml++ using xpath expression
#include <libxml++/libxml++.h>
xmlpp::NodeSet xmlP(std::string xml_string, std::string xpath) {
xmlpp::DomParser doc;
// 'response' contains your HTML
doc.parse_memory(xml_string);
xmlpp::Document* document = doc.get_document();
xmlpp::Element* root = document->get_root_node();
xmlpp::NodeSet elemns = root->find(xpath);
xmlpp::Node* element = elemns[0];
std::cout << elemns.size() << std::endl;
std::cout << element->get_line() << std::endl;
//const auto nodeText = dynamic_cast<const xmlpp::TextNode*>(element);
const auto nodeText = dynamic_cast<const xmlpp::ContentNode*>(element);
if (nodeText && nodeText->is_white_space()) //Let's ignore the indenting - you don't always want to do this.
{
std::cout << nodeText->get_content() << std::endl;
}
}
xml_string是这样的:
std::string xml_strings("
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo page</title></head>
<body>
<div class="item">
<div class="row">
<div class="col-xs-8">Item</div>
<div class="col-xs-4 value">
<script type="text/javascript">fruit('orange');</script>
</div></div></div>
</body></html>");
使用页面和 xpath 表达式调用的函数如下所示:xmlpp::NodeSet xmlNodes = xmlP(xml_strings, "/html/body/div/div/div[2]/script");
问题是我无法在<script>
内获取文本,我尝试dynamic_cast到ContentNode,没有任何帮助...
libxml++ 值得还是我需要用另一个 XML 库解决我的问题?
请,我感谢所有可以从<script>
标签中获得文本值的建议。
我尝试在本地重现您的问题,但无法root->find(xpath)
产生任何节点。 根据此问题,您需要告诉 XPath 您的节点位于哪个命名空间下,即使它是默认命名空间。
我更改了 XPath 字符串并find
调用,如下所示:
std::string xpath("/x:html/x:body/x:div/x:div/x:div[2]/x:script");
xmlpp::Node::PrefixNsMap nsMap = {{"x",root->get_namespace_uri()}};
xmlpp::Node::NodeSet elemns = root->find(xpath, nsMap);
xmlpp::Node* element = elemns[0];
const auto nodeText = dynamic_cast<const xmlpp::Element*>(element);
if (nodeText) {
std::cout << nodeText->get_first_child_text()->get_content() << std::endl;
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 你能重载对象变量名本身返回的内容吗
- 如何将内容数组写入文本文件?
- 试图让变量检查数组中的某些内容
- initializer_list中字符串的内容为何为空
- C++宏忽略之后的内容
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何知道QDataStream不能反序列化某些内容
- 即使我读取了所有内容,在FIFO上打开的QSocketNotifier也会一直启动
- 安装opencv失败-粘贴CMakeError.log的内容
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- gtkmm 显示文件内容
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 打印时有二叉树问题.用户输入不打印任何内容
- 为什么缓冲区的内容在读取空 rdbuf 时被删除?
- 在C++行尾写一个分号或多个分号是否会改变任何内容
- 链接列表运算符重载没有打印出我想要的内容
- 无法使用 <script> XPath 表达式通过 libxml++ 获取 XHTML 内容
- 通过 libxml 确定 Xpath 内容