laleh-poly has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I have a wired problem while parsing an XML file using LibXML. I googled it and unfortunately I could not find solution. Here is the code:
if (@files !=0){ foreach $file (@files) { $parser = XML::LibXML->new(); $tree = $parser->parse_file($file); $root = $tree->getDocumentElement; @changes = $root->getElementsByTagName('change'); foreach $change (@changes) { @classDetail = $change->getElementsByTagName('class'); if (@classDetail !=0){ $className=$classDetail[0]->getAttribute('name'); print "className= " .$className ."\n"; } } undef ($parser) } } closedir(DIR);
For some files it works fine, but for some other files it gives the error "Couldn’t create file parser context for file "somename.xml": No such a file or directory at... ". For example, I rename a file (for which parsing was successful) and then I rerun my scripts on both files. For the original file it works ok but on the copied one I receive the above mentioned error. However, the content of the two files are exactly the same, and just their names are different. Any idea? Thanks, Laleh

Replies are listed 'Best First'.
Re: Couldn’t create file parser context for file "somename.xml"
by ahmad (Hermit) on Dec 31, 2009 at 06:30 UTC

    No such file or directory. means you are attempting to open/parse a file that doesn't exists.

    Make sure you've got the right file name before attempting to parse it. Something like this might help

    # inside your foreach loop before parsing, check if the file does exis +ts if (-e $file ) { # parse the file }else{ print "$file doesn't exists\n"; }
      Thanks Ahmad, But both files exist. I deleted the file (the copied one) from the directory and run my script, every thing was fine, then I make a copy of this file and just changed its name (at this point two files are now in the directory). When i run the script for the second time, for the original file it works, but for the copied one, I get the error. But if i repeat the above process it works for both files. For every new file that I add to the directory it does not work for the first time but when I delete the file run the script, then again move the file to the directory it works!!! so wired.

        I bet you do something silly like `ls` and you don't properly extract the line feeds.

        Place the following just before the code you posted:

        use Cwd; use Data::Dumper; print("cwd = ", getcwd(), "\n"); print("files:\n", do { local $Data::Dumper::Useqq = 1; Dumper(\@files); });

        What do you get?