使用 libxml++ 从内容节点解析 html 文本返回空输出

问题描述 投票:0回答:1

我修改了在这里找到的 DOM 解析示例:https://libxmlplusplus.github.io/libxmlplusplus/manual/html/chapter-parsers.html#sect-dom-parser

代码:

#include <libxml++/libxml++.h>
#include <iostream>
#include <cstdlib>

int main(int argc, char* argv[])
{
  std::string filepath = "theHtml.html";

  try
  {
    xmlpp::DomParser parser;
    parser.parse_file(filepath);

    const auto pNode = parser.get_document()->get_root_node();
    for(const auto& child : pNode->get_children())
    {
        const auto nodeText = dynamic_cast<const xmlpp::TextNode*>(child);

        if(nodeText)
            {
              std::cout << "Text Node" << std::endl;
              std::cout << nodeText->get_content();
            }
    }
  }
  catch(const std::exception& ex)
  {
    std::cerr << "Exception caught: " << ex.what() << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<title>The title</title>
</head>

<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>

输出:

Text Node

Text Node


Text Node

21:05:13: qtProject exited with code 0

似乎 get_content() 函数在我修改后的代码中无法正常工作。当应该有文本时它返回空输出。未修改的示例编译并返回位于 html 文件中的文本。文档:https://fossies.org/dox/libxml++-5.0.2/classxmlpp_1_1ContentNode.html

编辑 这似乎有效:

#include <libxml++/libxml++.h>
#include <iostream>
#include <cstdlib>

void print_node(const xmlpp::Node* node)
{
  const auto nodeText = dynamic_cast<const xmlpp::TextNode*>(node);

  if(nodeText && nodeText->is_white_space())
    return;

  if(nodeText)
  {
    std::cout << "Text Node" << std::endl;
    std::cout << "text = \"" << nodeText->get_content() << "\"" << std::endl;
  }

    //Recurse through child nodes:
    for(const auto& child : node->get_children())
    {
      print_node(child);
    }

}

int main(int argc, char* argv[])
{
  std::string filepath;
  filepath = "theHtml.html";

  try
  {
    xmlpp::DomParser parser;
    parser.parse_file(filepath);

    if(parser)
    {
      //Walk the tree:
      const auto pNode = parser.get_document()->get_root_node();
      print_node(pNode);
    }
  }
  catch(const std::exception& ex)
  {
    std::cerr << "Exception caught: " << ex.what() << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

输出:

Text Node
text = "The title"
Text Node
text = "My First Heading"
Text Node
text = "My first paragraph."
22:56:58: qtProject exited with code 0
c++ libxml2
1个回答
0
投票

您的非工作版本正在查找文本节点,但它找到的文本节点只是 HTML 顶级元素之间的空白。它没有深入到树中以找到“真正的”文本节点。所以

get_content()
正在工作,只是它找到的内容都是空格、制表符和换行符。

你可以改变你的代码来输出这个

// output text with delimiters
std::cout << '|' << nodeText->get_content() << '|' << std::endl;

准确查看您的代码找到的文本。

你的第二个工作版本是递归的,所以它确实扫描了整棵树,所以它确实找到了所有的文本。

© www.soinside.com 2019 - 2024. All rights reserved.