Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter/narrow XML in Perl to ignore unwanted child elements?

Say I have the following XML structure (mock) that begins:

<site defaultDomain="www.somedomain.com">
    <supported-locales>
        <locale id="sometext"/>
    </supported-locales>
    <next-child-of-site>
    ...
</site>

I am using Mojo::DOM and trying to get only the id text of <locale> elements that are children of <supported-locales> elements and ignore all other children of <site>

# Parse XML
my $dom = Mojo::DOM->new->xml(1)->parse($xml);

for my $e ($dom->find('site[defaultDomain')->each) {
    say $e->children->join();
}

So I get this far, but am stuck on how to filter the children to <supported-locales> and then <locale> only. Suggestions? I'm new to XML processing with Mojo::DOM.

like image 764
sqldoug Avatar asked Dec 10 '25 00:12

sqldoug


1 Answers

You can look for locale tags that are underneath site and supported-locales tags directly using the child selector:

#!/usr/bin/env perl

use strict;
use warnings;

use feature qw(say);
use Mojo::DOM;

my $xml = q{
<site defaultDomain="www.somedomain.com">
    <supported-locales>
        <locale id="sometext"/>
    </supported-locales>
    <next-child-of-site>
</site>
};
my $dom = Mojo::DOM->new->xml(1)->parse($xml);

for my $e ($dom->find('site > supported-locales > locale')->each) {
   say $e->{id};
}
# output: sometext

As always, you should use strict; and use warnings;

like image 68
Hunter McMillen Avatar answered Dec 12 '25 16:12

Hunter McMillen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!