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

Hi guys

I have a big XML file, in this file I have for example this tag,
<Validation byCluster="true" byOtherPop="false" byHapMap="true" by1000G="true">
--------------------
The result should be: byCluster, byHapMap, by1000G
or this
<Validation bySASH="true" byOtherPop="true" byHapMap="true" by1000G="false">
--------------------
The result should be: bySASH, byOtherPop, byHapMap
========================
I want to print just the attributes "not their values" that have "true" as a value and ignore the attributes that have "false" as a value
I am using perl and twig::XML to extract these information.
I do not know even how to start because If I want the values, it would be easy, but have no information about how to print the attributes
Any advices about how to solve this

Thanks in advance

  • Comment on Print specific attributes "not their values" of an XML file using Perl

Replies are listed 'Best First'.
Re: Print specific attributes "not their values" of an XML file using Perl
by toolic (Bishop) on Sep 11, 2015 at 18:09 UTC
    XML::Twig atts is one way:
    use warnings; use strict; use XML::Twig; my $str = ' <Foo> <Validation byCluster="true" byOtherPop="false" byHapMap="true" by +1000G="true"/> </Foo> '; my $t = XML::Twig->new( twig_handlers => { Validation => \&valid }, ); $t->parse($str); sub valid { my ($t, $tag) = @_; my %atts = %{ $tag->atts() }; for my $att (keys %atts) { print "$att\n" if $atts{$att} eq 'true'; } } __END__ by1000G byCluster byHapMap

    UPDATE: runrig /msg'd me that only 'true' should be chosen.

Re: Print specific attributes "not their values" of an XML file using Perl
by runrig (Abbot) on Sep 11, 2015 at 18:08 UTC
    If you're up to using a different library, then:
    use warnings; use strict; use XML::Rules; my $xml = <<XML; <root> <Validation byCluster="true" byOtherPop="false" byHapMap="true" by1000 +G="true"/> </root> XML my @rules = ( Validation => sub { my $d = $_[1]; my @v = grep { $d->{$_} eq 'true' } keys %$d; print join(",", @v), "\n"; }, _default => undef, ); my $xr = XML::Rules->new( rules => \@rules ); $xr->parse($xml);
Re: Print specific attributes "not their values" of an XML file using Perl
by choroba (Cardinal) on Sep 11, 2015 at 22:47 UTC
    Using XML::XSH2, a wrapper around XML::LibXML:
    for //Validation/@*[.='true'] echo name() ;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ