开发者

How to extract a part of xml code from an xml file using Perl Script and move to separate files

I need a Perl Script to do the following process:

See the following XML code:

<booklist>
  <book>
    <author>Book 1 author 1</author>
    <author>Book 1 author 2</author>
    <title>Book 1 title</title>
    <isbn>Book1ISBN</isbn>
  </book>
  <book>
    <author>Book 2 author 1</author>
    <author>Book 2 author 2</author>
    <title>Book 2 title</title>
    <isbn>Book2ISBN</isbn>
  </book>
  <book>
    <author>Book 3 author 1</author>
    <author>Book 3 author 2</author>
    <author>Book 3 author 3</author>
    <title>Book 3 title</title>
    <isbn>Book3ISBN</isbn>
  </book&开发者_如何转开发gt;
</booklist>

how can i extract the portion

<book>
    <author>Book 3 author 1</author>
    <author>Book 3 author 2</author>
    <author>Book 3 author 3</author>
    <title>Book 3 title</title>
    <isbn>Book3ISBN</isbn>
</book>

and move to separate XML file using Perl?


You could use XML::Twig like this:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $t= XML::Twig->new( twig_roots => { book => \&book }, 
                       pretty_print => 'indented',
                     )
                ->parsefile( 'books.xml');

sub book
  { my( $t, $book)= @_;
    my $isbn= $book->field( 'isbn');
    if( $isbn eq 'Book3ISBN')
      { $book->cut->print_to_file( "$isbn.xml"); }
    else 
      { $t->flush; }
  }

This assumes that you are selecting the book to extract based on its ISBN, and that you want to output the initial file without that book.

If the criteria is something else, then adjust the test in book.

If you don't want to touch the original file, then remove the call to cut, and replace flush by purge (these methods throw away the previous elements in the tree so you don't use too much memory, if the initial file is small, then you don't need them)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜