XMLin() and XMLout() Methods

This section describes two key methods in the XML::Simple module, XMLin() and XMLout(), to convert XML text string into a hash structure representing the XML structure and to convert the hash back to a string.

XML::Simple module is an easy API to read and write XML files. It offers two main methods: XMLin() and XMLout().

XMLin(str) - Method to parse the XML input into a hash, and return the reference of the hash. The XML input can be specified in 3 ways:

XMLout(ref) - Method to write the hash pointed by the specified reference into an XML string, and return XML string.

If XML::Simple is installed as part of the ActivePerl package. No extra download and installation steps needed.

Here is a simple program to show you how to use XML:Simple:

#- XmlSimpleHello.pl
#- Copyright (c) 1999 by Dr. Herong Yang, http://www.herongyang.com/
#
   use XML::Simple;
   my $xs = new XML::Simple();
   my $ref = $xs->XMLin("<p>Hello world!</p>");
   my $xml = $xs->XMLout($ref);
   print $xml;
   exit;

Output:

<opt>Hello world!</opt>

It's interesting to see from the output that the <p> tag has been changed to <opt> during the read and write operations. This is because of the default setting of the option: keeproot. I will explain some of the important options later in this chapter.

Table of Contents

 About This Book

 Perl on Linux Systems

 ActivePerl on Windows Systems

 Data Types: Values and Variables

 Expressions, Operations and Simple Statements

 User Defined Subroutines

 Perl Built-in Debugger

 Name Spaces and Perl Module Files

 Symbolic (or Soft) References

 Hard References - Addresses of Memory Objects

 Objects (or References) and Classes (or Packages)

 Typeglob and Importing Identifiers from Other Packages

 String Built-in Functions and Performance

 File Handles and Data Input/Output

 Open Files in Binary Mode

 Open Directories and Read File Names

 File System Functions and Operations

 Converting Perl Script to Executable Binary

 Using DBM Database Files

 Using MySQL Database Server

 Socket Communication Over the Internet

XML::Simple Module - XML Parser and Generator

XMLin() and XMLout() Methods

 XML Parsing Options

 "forcearray" - Forcing Element Contents as Arrays

 "suppressempty" - Parsing Empty Elements

 "keyattr" - Namings Attributes as Keys

 XmlSimpleHash.pl - XML Hash Example

 XML Communication Model

 SOAP::Lite - SOAP Server-Client Communication Module

 Perl Programs as IIS Server CGI Scripts

 CGI (Common Gateway Interface)

 XML-RPC - Remote Procedure Call with XML and HTTP

 RPC::XML - Perl Implementation of XML-RPC

 Integrating Perl with Apache Web Server

 CGI.pm Module for Building Web Pages

 LWP::UserAgent and Web Site Testing

 References

 PDF Printing Version