-4

私は新しいXML-Twigです...パラタグを分割したい....

XML ファイル:

<xml>
   <p class="indent">text <i>text<i> incluce <div>text</div> ateas</p>
   <p class="text">text text incluce <div>text</div> <b>ateas<b></p>
   <p class="text">text <p>text</p> incluce <div>text</div> ateas</p>
</xml>

ここで、Para タグを分割します。どうすれば分割でき、インラインパラタグとdivタグなしでパラタグを割り当てることができます...

次のように出力する必要があります。

<xml>
<p class="indent">text <i>text</i> incluce</p>
<div>text</div>
<p class="indent">ateas</p>
<p class="text">text text incluce</p>
<div>text</div>
<p class="text"><b>ateas</b></p>
<p class="text">text</p>
<p>text</p>
<p class="text">incluce</p>
<div>text</div>
<p class="text">ateas</p>
</xml>

これどうやって割るんだろう……。

脚本:

#!/usr/bin/perl
use warnings;
use strict;
use XML::Twig;
open(my $output , '>', "output.xml") || die "can't open the Output $!\n";
my $xml = XML::Twig->new( twig_handlers => { p => \&split_tag } );
$xml->parsefile("sample.xml");
$xml->print($output);
sub split_tag {
my ($twig, $p) = @_;
$_->wrap_in('p', $p->atts) for $p->children('#TEXT');
$p->erase;
}

しかし、抽出出力を取得できません..どうすればこれを行うことができますか?

4

1 に答える 1

2

このコードは、新しい要件に一致しているようです。これでうまくいかない場合は、無料のコードを求める前に、自分で修正してみてください。

HTML ではネストされた<p>要素が違法であるため、サンプル データの 3 行目を無視しました。

use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig->new(
  twig_handlers => { p => \&split },
  pretty_print => 'indented',
);

$twig ->parsefile('sample.xml');
$twig->print_to_file('output.xml');

sub split{
  my ($twig, $p) = @_;
  return if $p->contains_only_text;

  my @children = $p->cut_children;
  my @newchildren;

  my $newpara = $p->copy;
  for my $child (@children) {
    if ($child->is_elt and $child->tag eq 'div') {
      push @newchildren, $newpara if $newpara->has_children;
      push @newchildren, $child;
      $newpara = $p->copy;
    }
    else {
      $child->paste(last_child => $newpara);
    }
  }

  push @newchildren, $newpara if $newpara->has_children;
  $p->replace_with(@newchildren);
}

出力

<xml>
  <p class="indent">text <i>text</i> incluce </p>
  <div>text</div>
  <p class="indent"> ateas</p>
  <p class="text">text text incluce </p>
  <div>text</div>
  <p class="text"> <b>ateas</b></p>
  <p class="text">text <p>text</p> incluce </p>
  <div>text</div>
  <p class="text"> ateas</p>
</xml>
于 2013-01-07T07:01:47.110 に答える