How to read root tag and root closing tag to a Perl variable?

前端 未结 1 1803
遇见更好的自我
遇见更好的自我 2021-01-24 18:07

I am new to Perl. I want to read the xml root tag and root end tag to a perl variable.

I tried this normal file reading. It worked. I am getting fist line and last line.

1条回答
  •  盖世英雄少女心
    2021-01-24 18:26

    I don't know how to use xml_split program, but here you have an approach using XML::Twig module, where I create new elements and move each pair of childs from one tree to another one:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    use XML::Twig;
    use POSIX qw;
    
    my ($split_limit, $n) = (2, 0); 
    
    my $twig = XML::Twig->new->parsefile( shift );
    my $root = $twig->root;
    
    for (  1 .. ceil( $root->children_count / $split_limit ) ) { 
        my $t = XML::Twig::Elt->new( $root->tag, $root->atts );
        for ( 1 .. $split_limit ) { 
            my $children = $root->first_child;
            last unless $children;
            $children->move( last_child => $t );
        }   
        $t->print_to_file( 'xmlfile-' . $n++ . '.xml' );
    }
    

    Run it like:

    perl script.pl xmlfile
    

    That yields one file for each pair of childs of root with its header:

    ==> xmlfile-0.xml <==
    11
    ==> xmlfile-1.xml <==
    11
    ==> xmlfile-2.xml <==
    11
    

    0 讨论(0)
提交回复
热议问题