Search code examples
xmlperldommojolicious

In Perl using Mojo::DOM in XML mode, how do I match on contents of subtags?


I have the following XML:

<Product>
  ...
    <TitleDetail>
      <TitleType>01</TitleType>
      <TitleElement>
        <TitleElementLevel>01</TitleElementLevel>
        <TitleText>This is the title I'm looking for</TitleText>
      </TitleElement>
    </TitleDetail>
  ...
</Product>

(It's ONIX, if you're curious.)

I want to extract the title, of type 01. I've tried:

say $dom->at('TitleDetail[TitleType="01"] > TitleElement > TitleText')

but that doesn't work. Looks like the tag[attr=value] syntax really only works for attributes.

Is there a simple way to do what I want?


Solution

  • It can be done with Mojo::DOM, but it's long. A couple of times there are Mojo::Collections in there, so you need to get the first element out.

    use Mojo::DOM;
    
    my $dom = Mojo::DOM->new->xml(1)->parse($xml);
    say $dom->find("TitleType")->grep(sub{ $_->text eq "01"})->first
        ->following("TitleElement")->first->at("TitleText")->text;