2013-01-07 83 views
-4

我新的XML-小枝...我想分裂對標籤....如何在不移動的情況下分割div標籤?

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> 

在這裏我要分段落標記。我怎麼可以拆分和如何分配不在線對標籤和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

這是一種可怕的問題。你所做的只是從你的[上一個問題](http://stackoverflow.com/questions/14156289)複製了其中一個解決方案,並在你發現它不能滿足你的所有需求時直接回來。我希望你已經嘗試了*某些東西*讓它爲你自己工作 - 這不是一個你可以免費獲得某人爲你工作的網站。即使您發佈的示例數據也不是有效的XML。 – Borodin

回答

2

此代碼似乎符合您的新要求。如果這不起作用嘗試自己解決它之前要求更多的免費代碼。

我忽略了樣本數據的第三行,因爲嵌套的<p>元素在HTML中是非法的。

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> 
相關問題