in reply to How do I ignore comments in an xml file when using win32::ole?

Here is a Twig::XML solution:
use warnings; use strict; use XML::Twig; my $str = <<EOF; <?xml version="1.0" encoding="UTF-8"?> <Header> <Main id="1" name="Item1"> </Main> <Main id="2" name="Item2"> </Main> <!--Main id="3" name="Item4"> </Main--> <Main id="4" name="Item5"> </Main> </Header> EOF my $t = XML::Twig->new(twig_handlers => { Main => sub {print $_->att('id'), "\n"} }); $t->parse($str); __END__ 1 2 4
  • Comment on Re: How do I ignore comments in an xml file when using win32::ole?
  • Download Code

Replies are listed 'Best First'.
Re^2: How do I ignore comments in an xml file when using win32::ole?
by ketanh (Novice) on Jun 25, 2011 at 19:37 UTC

    @choroba, I'm a mere systems engineer trying to parse xml :) I've used xml::simple before, but that doesn't work with the file I have now. So I went with the search that gave me the easiest example to read and follow.

    @toolic, Thanks for the example. I didn't know what to do with the xml that you added into the code. I tried reading it in a few ways, didn't help. I have to read a file that I download from a repository and have to load it into my parser
    However, thanks to your example, I explored XML::TWIG more and figured out a way to do this.
    This link was very helpful
    http://www.xml.com/pub/a/2001/04/18/perlxmlqstart1.html

    use warnings; use strict; use XML::Twig; my $file = './test.xml'; my $twig = XML::Twig->new(); $twig->parsefile($file); my $root = $twig->root; foreach my $item ($root->children('Main')){ print $item->att('id').", ".$item->att('name'); print "\n"; }

    This gave me the desired output.
    1, Item1
    2, Item2
    4, Item5

    @AnomalousMonk, I won't claim to be any sort of expert with xml. To me, if internet explorer grey'ed it out, and Visual SlickEdit "green"ed it out, I take it it's a comment in the XML. :)

    Thanks for all your help!

      I didn't know what to do with the xml that you added into the code. I tried reading it in a few ways, didn't help. I have to read a file that I download from a repository and have to load it into my parser
      XML::Twig is flexible in that it allows you to parse either a file (as you have done) or a Perl scalar variable (as I have done). Using the latter is merely for the convenience of creating a small self-contained code sample.