artist has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I have several dynamically generated XML files in a directory, and I like to take certain fields and values from it and build a index.xml file.

I can combine the files into a single string, strip some headers and get the value what I want. I am looking for cleaner apporach. I discussed this in CB for a while. Either Perl based or XSLT based solution would be good.

Thanks,

Update: Here is the example: There are multiple files in given directory.

#File1.xml
<root>
<person>
<name>John</name>
<age>23</age>
<city>New York</city>
</person>

<person>
<name>Marry/name>
<age>22</age>
<city>London</city>
</person>
</root>

#File2.xml
<root>
<person>
<name>Joe </name>
<age>25</age>
<city>Huston</city>
</person>
</root>

#index.xml
<friends>
  <person>
    <name>John</name>
    <age>23<age>
  </person>
  <person>
    <name>Marry</name>
    <age>22<age>
  </person>
  <person>
    <name>Joe</name>
    <age>25<age>
  </person>
</friends>
<person>

artist

Replies are listed 'Best First'.
Re: Building XML Index File
by mirod (Canon) on Feb 19, 2004 at 20:57 UTC

    This looks like a perfect fit for XML::Twig. If you post an example of your data and of the result you want to get I can be more precise.

    As for whether it would be considered clean... ;--)

Re: Building XML Index File
by borisz (Canon) on Feb 19, 2004 at 20:47 UTC
    If your task is so easy ( just get some fields and values ) XML::XPath may an option too. Or use XML::Simple or XML::Smart for not so large files. Or the most flexible way is to use XML::SAX read XML::SAX::Intro if you have not done already. Or use XSLT but IMHO it is complicated for anything that does something with the data.
    Boris
Re: Building XML Index File
by mirod (Canon) on Feb 20, 2004 at 16:42 UTC

    With this data you can use the following code, which is quite optimized to use the least possible memory, just in case you have _LOTS_ of friends ;--):

    #!/usr/bin/perl -w use strict; use XML::Twig; # initialize the index document # pretty_print => 'indented' gives you exactly the output you showed my $index= XML::Twig->new( pretty_print => 'record_c') ->parse( '<friends/>'); my $friends= $index->root; foreach my $file (@ARGV) { my $friend; # the current friend my $t= XML::Twig->new( start_tag_handlers => { # create a new friend in the inde +x person => sub { $friend= $friends +->insert_new_elt( last_child => 'person') } }, twig_roots => { # store the elements in the frien +d 'person/name' => sub { $_->move( +last_child => $friend); }, 'person/age' => sub { $_->move( +last_child => $friend); } } ) ->parsefile( $file); } $index->print;
Re: Building XML Index File
by diotalevi (Canon) on Feb 19, 2004 at 18:54 UTC
    See the XSLT document() function and possibly O'Reilly's XSLT book chapter seven.