2013-01-07 85 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> 
相关问题