XML

XML::LibXML

Sample XML file

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd instock="yes">
<title>Pyschedelic Rock</title>
</cd>
<cd instock="no">
<title>Techno Beat</title>
</cd>
</catalog>

Read

Using XML DOM
use strict;
use XML::LibXML;

my $parser = XML::LibXML->new();
my $tree = $parser->parse_file('catalog.xml');
my $root = $tree->getDocumentElement;

foreach my $cd_node ($root->getElementsByTagName('cd')) {
# Text value
my $title = ($cd_node->getElementsByTagName('title'))[0]->getFirstChild->getData;;

# Attribute
my $instock = $cd_node->getAttribute('instock');

print $title . " " . (($instock eq "yes") ? "[In stock]" : "[Out of stock]") . "\n";
}
print "\n";
Using XPath
use strict;
use XML::LibXML;

my $parser = XML::LibXML->new();
my $tree = $parser->parse_file('catalog.xml');
my $root = $tree->getDocumentElement;

foreach my $entry_node ($root->findnodes('cd')) {
# Text value
my $title = $entry_node->findvalue('title');

# Attribute
my $instock = $entry_node->findvalue('@instock');

print $title . " " . (($instock eq "yes") ? "[In stock]" : "[Out of stock]") . "\n";
}
print "\n";

Write

Using XML DOM
use strict;
use XML::LibXML;

sub create_cd_node {
my ($doc, $title, $instock) = @_;
my $cd_node = $doc->createElement('cd');

# Child node
my $title_node = $doc->createElement('title');
$title_node->appendChild(XML::LibXML::Text->new($title));
$cd_node->appendChild($title_node);

# Attribute
$cd_node->setAttribute('instock', $instock);
return $cd_node;
}

# Document
my $doc = XML::LibXML::Document->new();
$doc->setEncoding('UTF-8');

# Root node
my $root = $doc->createElement('catalog');
$doc->setDocumentElement($root);

# Child cd nodes
$root->appendChild(&create_cd_node($doc, 'Psychedelic Rock', 'yes'));
$root->appendChild(&create_cd_node($doc, 'Techno Beat', 'no'));

print $doc->toString;

Resources URL: 
notes/perl/resources
Sources URL: 
notes/perl/sources

See Also