Perl (Scripting) - XML::Twig loop through tags (first_child children)

Let's say foo.xml contains the following.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<food>
  <name>Apple</name>
</food>

 

The following would print the entire XML.

#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;

my $twig = new XML::Twig( pretty_print => 'indented' );
$twig->parsefile('foo.xml');
$twig->print;

 

Which should return the following.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<food>
  <name>Apple</name>
</food>

 

children can be used to only print the <name> tag.

foreach my $name ($twig->root->children('name')) {
  $name->print;
}

 

Which should return the following.

  <name>Apple</name>

 

Notice in this example that there are three tags (food, fruit, name).

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<food>
  <fruit>
    <name>Apple</name>
  </fruit>
</food>

 

first_child and children can be used to only print the <name> tag.

foreach my $name ($twig->root->first_child('fruit')->children('name')) {
  $name->print;
}

 

Which should return the following.

  <name>Apple</name>

 

Notice in this example that there are two fruit tags.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<food>
  <fruit>
    <name>Apple</name>
  </fruit>
  <fruit>
    <name>Orange</name>
  </fruit>
</food>

 

In this scenario, foreach loops can be used.

foreach my $fruit ($twig->root->children('fruit')) {
  foreach my $name ($fruit->children('name')) {
    $name->print;
  }
}

 

Which should return the following.

  <name>Apple</name>
  <name>Orange</name>

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 7fe53 in the box below so that we can be sure you are a human.