【问题标题】:how can I remove tag only我怎样才能只删除标签
【发布时间】:2012-11-09 07:29:07
【问题描述】:

我只需要在 xml 文件中删除一些标签。

xml:

<p>Originally published <xref ref-type="bibr" rid="ref155">Klein, F. (1978)</xref> <i>Priam Books. Reproduced by permission of the author.</p>

脚本:

use XML::Twig;
my $xml_twig_content = XML::Twig->new(
keep_encoding => 1,
twig_handlers => {
keep_atts_order => 1,
'xref' => \&xref,
},
pretty_print => 'indented',
);
$xml_twig_content->parsefile('sample.xml');

sub xref {
 my ($xml_twig_content, $xref) = @_;
 my $XrefName = $xref->att('ref-type');
 if ($XrefName =~ /^bibr$/si){
 $xref->delete;
 }
}

我得到了输出:

<p>Originally published <i>Priam Books. Reproduced by permission of the author.</p>

我需要输出:

<p>Originally published Klein, F. (1978) <i>Priam Books. Reproduced by permission of the author.</p>

如何删除外部参照标签并保留其内容?

【问题讨论】:

    标签: xml perl xml-twig


    【解决方案1】:

    您可以使用erase-method:

    erase

    擦除元素:删除元素并将其所有子元素粘贴到其位置。

    这是你的sub 使用它:

    sub xref {
      my ( $twig, $xref ) = @_;
      $xref->erase;
    }
    

    请注意,对我来说,您的示例 XML 没有解析,因为 &lt;i&gt; 没有关闭。

    【讨论】:

      【解决方案2】:

      为什么keep_encoding =&gt; 1 位在twig_handlers 位内?文档中有什么错误吗?

      我会以更简单的方式执行此操作,使用 twig_roots/twig_print_outside_roots 传递除您感兴趣的 xrefs 之外的所有内容:

      #!/usr/bin/perl
      
      use strict;
      use warnings;
      
      use XML::Twig;
      
      XML::Twig->new( keep_encoding => 1,
                      twig_roots => { 'xref[@ref-type=~/^(?i:bibr)/]' => sub { print $_->inner_xml; } },
                      twig_print_outside_roots => 1,
                    )
               ->parsefile('sample.xml');
      

      twig_roots 选项仅针对正确的xrefs 触发。 @ref-type=~/^(?i:bibr)/] 位使用 XPath 的 XML::Twig 扩展,让您可以像在 Perl 中一样使用正则表达式,(?i: 部分使其不区分大小写。对于这些元素,打印内部 XML,而不是标签。

      twig_print_outside_rootsoption(我知道这是一个很长的选项名称!)导致除外部参照元素之外的所有内容都按原样输出,因此您不必担心保持属性顺序或缩进,它会与原始 XML 中的相同。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-02
        • 2021-10-02
        相关资源
        最近更新 更多