【问题标题】:perl XML::LibXML get direct child text node contentperl XML::LibXML 获取直接子文本节点内容
【发布时间】:2019-10-14 08:47:06
【问题描述】:

就像在这个 sn-p 中:

<p>content 1 of p <span>content of span</span> content 2 of p </p>

我只想获得以下内容: content 1 of pcontent 2 of p,而不是 content of span

有办法吗?

【问题讨论】:

  • 不要听@Nilesh Jain; XML::Simple 自己的文档警告您不要使用它,原因在Why is XML::Simple "discouraged"? 中列出。简而言之,这是一个极难使用的模块。简单地需要 $node-&gt;findnodes('text()') 和 XML::LibXML 会非常复杂并且容易出错。
  • 不要使用XML::Simple。它在很多年前就已经占有一席之地,但它自己的作者在它自己的文档中一直不鼓励它的使用多年。 (去实际阅读@NileshJain 提供的链接上的first 段落。)它自己的作者写了一个关于另一个模块的教程(XML::LibXML,这是一个很好的教程)。使用XML::LibXMLXML::Twig

标签: perl xml-libxml


【解决方案1】:

使用 XPath:

for my $text_node ($node->findnodes('text()')) {
   say $text_node;
}

不使用 XPath:

for my $child_node ($node->childNodes()) {
   next if $child_node->nodeType != XML_TEXT_NODE;

   say $child_node;
}

两者都输出以下内容:

content 1 of p
 content 2 of p

程序的其余部分:

use strict;
use warnings;
use feature qw( say );

use XML::LibXML qw( XML_TEXT_NODE );

my $xml = '<p>content 1 of p <span>content of span</span> content 2 of p </p>';

my $doc = XML::LibXML->new->parse_string($xml);
my $node = $doc->documentElement();

【讨论】:

  • 谢谢@ikegami 这很有帮助。 XPath 方法很简洁。
  • 当然,您可以将它嵌入到更大的 XPath 中(例如 $doc-&gt;findnodes('/p/text()')
猜你喜欢
  • 2013-03-04
  • 2020-08-05
  • 2022-01-28
  • 2012-08-04
  • 2015-02-20
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 2016-08-18
相关资源
最近更新 更多