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

Updated:   |  Perl (Scripting) articles

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



Comments


Add a Comment


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