Leser: 17
1
2
3
4
5
6
7
8
while (my $line2 = <FILE2>) {
if ($line2 =~ m/(?=Block \d+: .*)/ .. $line2 =~ m/______________/){
push (my @text, $line2);
foreach $text(@text) {
$text =~s/Block \d+: .*//;
$text =~s/\n//;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<items>
<find-spot id="12" nr="8" lnr="21" >
<token1>bla</token1>
<token2>blu</token2>
<environment>blub</environment>
</find-spot>
<find-spot id="13" nr="8" lnr="21" >
<token1>bla2</token1>
<token2>blu2</token2>
<environment>blub2</environment>
</find-spot>
</items>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
use strict; use warnings; use XML::LibXML; my $parser = XML::LibXML->new(); my $doc = $parser->parse_file("xml.xml"); my @nodes = $doc->findnodes('/items/find-spot'); my $i = 0; my @blocks = do { local $/ = "\n______________\n"; <DATA> }; for my $node (@nodes) { my $block = $blocks[$i]; my ($header, @lines) = split /\n/, $block; pop @lines; for my $line (@lines) { my $child = $node->addNewChild( "", "environment" ); $child->appendText("$line"); } $i++; } my $docstring = $doc->toString(); print "Neues XML: $docstring\n"; __DATA__ Block 1: perl1 perl2 perl3 ______________ Block 2: bla etc. ______________
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#!/usr/bin/perl use strict; use warnings; use XML::Simple; my $file_add='test.txt'; my $file_xml='text.xml'; my @blocks=parse_file($file_add); my $xml=XMLin($file_xml); # hier das "items" passend ersetzen my $data_add=$xml->{items}->{'find-spot'}; for my $pos (0..$#blocks) { my $data_val=$blocks[$pos]; next unless($data_val); if(ref($data_add) eq 'ARRAY') { next unless($data_add->[$pos]); $data_add=$data_add->[$pos]; } if(exists($data_add->{environment})) { if(ref($data_add->{environment}) eq 'ARRAY') { push(@{$data_add->{environment}},@$data_val) } else { $data_add->{environment}=[$data_add->{environment},@$data_val]; } } else { $data_add->{environment}=\@$data_val; } } print XMLout($xml); ######################################################################## sub parse_file { my $file=shift; my @blocks=(); local $/='______________'; open(my $fh, '<', $file) or die("ERROR open $file ($!)\n"); while(my $block=<$fh>) { my @data=(); my $id=@blocks; for my $line (split("[\r\n]+",$block)) { next unless($line); if($line=/^\s*Block\s*(\d+):/) { $id=$1; next; } push(@data,$line); } $blocks[$id]=\@data; } close($fh); return @blocks; }