FreeKB - Perl (Scripting) XML::Twig print values (text)
Perl (Scripting) - XML::Twig print values (text)

Let's say foo.xml contains the following.

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

 

Here is how you would parse foo.xml and print the XML tags using XML::Twig.

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

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

 

The following should be returned.

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

 

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

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

 

Which should return the following.

  <name>Bugs Bunny</name>

 

text can be used to only print the value in a tag.

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

 

Which should return the following.

Bugs Bunny


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 84d1b in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |