XML-Mini-1.38/0002755000076400007670000000000010751724614013025 5ustar malcalypsecorbaXML-Mini-1.38/Changes0000644000076400007670000000556510751724501014324 0ustar malcalypsecorbaRevision history for Perl extension XML::Mini XML-Mini-1.38, 2008.02.04 - Fixed bug - Can now handle empty attributes="" - Fix for annoying deep recursion warnings - header putting version attribute first, as prefered by xmllint etc. XML-Mini-1.34, 2008.02.03 ------------------------- - Added a preliminary check to XML::Mini::Document::fromString so we don't even try to parse XML that's clearly bad (uneven number of ... because of mistake of bad (without closing /). XML-Mini-1.28, 2003.03.31 ------------------------- - New XML::Mini::Document methods, toHash() and fromHash(), allow for wickedly easy XML generation and manipulation. See the XML::Mini::Document::fromHash() and XML::Mini::Document::toHash() pod for details. - Bug in the parsing algorithm when dealing with multiple elements of the same name, some of which have sub-elements, eg ... Now fixed. XML-Mini-1.27, 2003.02.01 ------------------------- - Problem for users of Perl < 5.8.0 - The module was coded as if Text::Balanced was optional but was 'use'ing it and failing the make test. - Made some changes to the parameters for getElement() and getElementByPath(), adding optional positions in order to allow extraction of the nth matching element instead of only the 1st. XML-Mini-1.26, 2003.01.27 ------------------------- - Big bug found when using Text::Balanced (problem in parsing ... whenever ... contains something like tags or anything but .. and text). Fixed and tests adjusted. XML-Mini-1.25, 2003.01.26 ------------------------- - Major changes to the parsing algorithm which, if Text::Balanced is available, allow "cross-nested" tags (such as ..) to be parsed successfully. - are now represented as XML::Mini::Element::Header elements - Added the XML::Mini::Document::header() method to create the new XML::Mini::Element::Header elements which represent . - Added the XML::Mini::Document::parse() method which accepts strings, filenames, open file handles and opened FileHandle objects - Currently beta-testing an XML::Mini replacement parser for the RPC::XML package XML-Mini-1.24, 2002.12.16 ------------------------- - Included Nigel Wetters (rivalsdm.com) changes/bug fixes to XML::Mini in order to make it more compatible with older Perl installs - Fixes to getElement (inability to fetch nested tags of same name) - Added the ability to removeChild() and removeAllChildren() for Element objects - Added the ability to prependChild() and insertChild(CHILD, INDEX) XML-Mini-1.24, 2002.11.25 ------------------------- - Made compatible with early Perls. - test added to check whether modules parse correctly - some rearrangement of PODs XML-Mini-1.2, 2002.09.15 ------------------------- - Perl implementation of MiniXML API finalised and Makefile.PL created XML-Mini-1.38/Makefile.PL0000644000076400007670000000055710751652671015007 0ustar malcalypsecorbause ExtUtils::MakeMaker; use strict; $^W = 1; my $PACKAGE = 'XML::Mini'; (my $PACKAGE_FILE = $PACKAGE) =~ s|::|/|g; WriteMakefile( NAME => $PACKAGE, VERSION_FROM => "lib/$PACKAGE_FILE.pm", # finds $VERSION PREREQ_PM => { 'FileHandle' => 2.0, 'Data::Dumper' => 2.1, 'Text::Balanced' => 1.95, } ); XML-Mini-1.38/MANIFEST0000644000076400007670000000121510751724614014153 0ustar malcalypsecorbaChanges INSTALL lib/XML/Mini/Document.pm lib/XML/Mini/Element/CData.pm lib/XML/Mini/Element/Comment.pm lib/XML/Mini/Element/DocType.pm lib/XML/Mini/Element/Entity.pm lib/XML/Mini/Element/Header.pm lib/XML/Mini/Element.pm lib/XML/Mini/Node.pm lib/XML/Mini.pm lib/XML/Mini/TreeComponent.pm LICENSE Makefile.PL MANIFEST README t/01parseable.t t/02parsexml.t t/03genxml.t t/04crossnested.t t/05parsefunc.t t/06getelem.t t/07ToFromHash.t t/08voicexml.t t/09invalidxml.t t/10removechild.t t/sample/invalid.xml t/sample/vocpboxes.xml t/sample/voicexmlbbs.vxml t/sample/xnested.xml META.yml Module meta-data (added by MakeMaker) XML-Mini-1.38/META.yml0000644000076400007670000000064010751724614014274 0ustar malcalypsecorba# http://module-build.sourceforge.net/META-spec.html #XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX# name: XML-Mini version: 1.38 version_from: lib/XML/Mini.pm installdirs: site requires: Data::Dumper: 2.1 FileHandle: 2 Text::Balanced: 1.95 distribution_type: module generated_by: ExtUtils::MakeMaker version 6.30 XML-Mini-1.38/t/0002755000076400007670000000000010751724614013270 5ustar malcalypsecorbaXML-Mini-1.38/t/01parseable.t0000644000076400007670000000114610524222226015542 0ustar malcalypsecorbause Test; use strict; $^W = 1; # play nice with old perl BEGIN { plan tests=>1 } use XML::Mini; use XML::Mini::Document; use XML::Mini::Element; use XML::Mini::Node; use XML::Mini::TreeComponent; use XML::Mini::Element::CData; use XML::Mini::Element::Comment; use XML::Mini::Element::DocType; use XML::Mini::Element::Entity; require XML::Mini; require XML::Mini::Document; require XML::Mini::Element; require XML::Mini::Node; require XML::Mini::TreeComponent; require XML::Mini::Element::CData; require XML::Mini::Element::Comment; require XML::Mini::Element::DocType; require XML::Mini::Element::Entity; ok(1);XML-Mini-1.38/t/05parsefunc.t0000644000076400007670000000153610751723140015604 0ustar malcalypsecorbause Test; use strict; $^W = 1; # play nice with old perl BEGIN { plan tests=> 4 } use FileHandle; require XML::Mini::Document; use strict; # Tests the various values passed through the parse() call my $sample = './t/sample/vocpboxes.xml'; my $numBoxes = 20; { my $miniXML = XML::Mini::Document->new(); my $numchildren = $miniXML->parse($sample); ok($numchildren, 3); $miniXML->init(); if (! open(INFILE, "<$sample")) { ok(0); } $numchildren = $miniXML->parse(*INFILE); ok($numchildren, 3); $miniXML->init(); my $fhObj = FileHandle->new(); $fhObj->open($sample); $numchildren = $miniXML->parse($fhObj); ok($numchildren, 3); $miniXML->init(); $fhObj = FileHandle->new(); $fhObj->open("<$sample"); my $contents = join('', $fhObj->getlines()); $fhObj->close(); $numchildren = $miniXML->parse($contents); ok($numchildren, 3); } XML-Mini-1.38/t/06getelem.t0000644000076400007670000000167610524222226015243 0ustar malcalypsecorbause Test; use strict; $^W = 1; # play nice with old perl BEGIN { plan tests=> 5 } use FileHandle; require XML::Mini::Document; use strict; my $XMLString = qq| bob ralph cindy Noam Chomsky |; { my $miniXML = XML::Mini::Document->new(); my $numchildren = $miniXML->parse($XMLString); ok($numchildren, 2); my $name1 = $miniXML->getElement('person')->getValue() || ok(0); ok($name1, 'bob'); my $name3 = $miniXML->getElement('person', 3)->getValue() || ok(0); ok($name3, 'cindy'); my $name2 = $miniXML->getElementByPath('people/person', 1, 2)->getValue(); ok($name2, 'ralph'); my $people = $miniXML->getElement('people') || ok(0); my $noam = $people->getElementByPath('person/name/first',4)->getValue(); ok($noam, 'Noam'); } XML-Mini-1.38/t/02parsexml.t0000644000076400007670000000216710751723056015455 0ustar malcalypsecorbause Test; use strict; $^W = 1; # play nice with old perl BEGIN { plan tests=> 46 } use FileHandle; require XML::Mini::Document; use strict; my $sample = './t/sample/vocpboxes.xml'; my $numBoxes = 20; { my $miniXML = XML::Mini::Document->new(); my $numchildren = $miniXML->fromFile($sample); ok($numchildren, 3); my $vocpBoxList = $miniXML->getElementByPath('VOCPBoxConfig/boxList') || ok(0); ok(1); $numchildren = $vocpBoxList->numChildren(); ok($numchildren, $numBoxes); my $childList = $vocpBoxList->getAllChildren(); ok($childList); ok(scalar @{$childList}, $numBoxes); foreach my $child (@{$childList}) { my $childName = $child->name(); ok($childName, '/^box$/', "boxList child with invalid name (should be 'box')"); my $boxnum = $child->attribute('number'); ok($boxnum, '/\d+$/', "box with invalid number (should be all digits)"); } my $inputFileHandle = FileHandle->new(); unless ($inputFileHandle->open("<$sample")) { ok(0); } my $sampleFile = join('', $inputFileHandle->getlines()); $inputFileHandle->close(); my $xmlOut = $miniXML->toString(); ok($xmlOut, $sampleFile); } XML-Mini-1.38/t/10removechild.t0000644000076400007670000000150110751723246016112 0ustar malcalypsecorbause Test; use strict; $^W = 1; # play nice with old perl BEGIN { plan tests=> 4 } use FileHandle; require XML::Mini::Document; use strict; my $sample = './t/sample/vocpboxes.xml'; my $numBoxes = 20; my $resultAfterDeletes = qq| root 0=998,1=011,2=012 |; { my $miniXML = XML::Mini::Document->new(); my $numchildren = $miniXML->fromFile($sample); ok($numchildren, 3); my $vocpBoxList = $miniXML->getElementByPath('VOCPBoxConfig/boxList') || ok(0); ok(1); $numchildren = $vocpBoxList->numChildren(); ok($numchildren, $numBoxes); my $firstBox = $vocpBoxList->getElement('box'); $firstBox->removeChild('message'); my $testtag = $firstBox->getElement('testtag'); $firstBox->removeChild($testtag); ok($firstBox->toString(), $resultAfterDeletes); } XML-Mini-1.38/t/08voicexml.t0000644000076400007670000000072010751674631015453 0ustar malcalypsecorbause Test; use strict; $^W = 1; # play nice with old perl BEGIN { plan tests=> 3 } use FileHandle; require XML::Mini::Document; use strict; my $textBalancedUnavail; my $sample = './t/sample/voicexmlbbs.vxml'; { my $miniXML = XML::Mini::Document->new(); my $numchildren = $miniXML->fromFile($sample); ok($numchildren, 3); my $vxml = $miniXML->getElement('vxml'); ok($vxml); my $forms = $vxml->getAllChildren('form'); ok(scalar @{$forms}, 9); } XML-Mini-1.38/t/03genxml.t0000644000076400007670000000401110524222226015072 0ustar malcalypsecorbause Test; use strict; $^W = 1; # play nice with old perl BEGIN { plan tests=> 101 } use XML::Mini::Document; use strict; my $expectedXML = qq|\n| .qq| \n| .qq| hola\n| .qq| \n| .qq| \n| .qq|halo & hola\n| .qq| \n| .qq| \n| .qq| \n| .qq| \n| .qq| \n\n|; { my $miniXMLDoc = XML::Mini::Document->new(); my $xmlRootNode = $miniXMLDoc->getRoot(); ok($xmlRootNode); my $xmlHeader = $xmlRootNode->header('xml'); $xmlHeader->attribute('version', '1.0'); my $containerTag = $xmlRootNode->createChild('mycontainer'); my $tag1 = $containerTag->createChild('tag1', 'hola'); ok($tag1); my $tag2 = $containerTag->createChild('tag2'); ok($tag2); $tag2->attribute('stuff', 'bla'); my $orphan = $miniXMLDoc->createElement('tag3'); ok($orphan); $orphan->text('halo & hola'); $containerTag->appendChild($orphan); $orphan->attribute('stuff', 'morestuff'); my $insideEl = $orphan->createChild('inside'); $insideEl->attribute('joke', 'hah'); my $tag4 = $containerTag->createChild('tag4'); my $outsider = $xmlRootNode->createChild('theoutcast'); my $xmlOutput = $miniXMLDoc->toString(); ok($xmlOutput); ok($xmlOutput, $expectedXML); my $pathStr = ''; my $leafChild = $tag4; for(my $i=0; $i<90; $i++) { $pathStr .= '/nested'; $leafChild = $leafChild->createChild('nested'); ok($leafChild); } $leafChild->text('--> Where Am I <--'); $pathStr =~ s|^/(.+)$|$1|; my $foundElement = $xmlRootNode->getElementByPath($pathStr); ok($foundElement); my $text = $foundElement->getValue(); ok($text, '--> Where Am I <--'); my $removedChild = $xmlRootNode->removeChild($outsider); my $newNumChildren = $xmlRootNode->numChildren(); ok($newNumChildren, 2); my $prepended = $orphan->prependChild($removedChild); ok($prepended); my $retList = $orphan->removeAllChildren(); $newNumChildren = $orphan->numChildren(); ok($newNumChildren, 0); } XML-Mini-1.38/t/07ToFromHash.t0000644000076400007670000000666210751723233015642 0ustar malcalypsecorbause Test; use strict; $^W = 1; # play nice with old perl BEGIN { plan tests=> 11 } use FileHandle; require XML::Mini::Document; use Data::Dumper; use strict; my $sample = './t/sample/vocpboxes.xml'; my $numberOfBoxes = 20; { my $miniXML = XML::Mini::Document->new(); my $numchildren = $miniXML->parse($sample); ok($numchildren, 3); my $XMLhash = $miniXML->toHash(); my $boxes = $XMLhash->{'VOCPBoxConfig'}->{'boxList'}->{'box'}; ok($boxes); ok(ref $boxes, 'ARRAY'); my $numBoxes = @{$boxes}; ok($numBoxes, $numberOfBoxes); #print STDERR Dumper($XMLhash); my $attribs = { 'attributes' => { '-all' => [ 'id', 'number', 'version'], 'email' => 'type', }, }; my $newDocHash = { 'person' => [ { 'id' => '001', 'name' => 'Pat D', 'type' => 'SuperFly SuperSpy', 'email' => [ { 'type' => 'public', '-content' => 'spam-me@psychogenic.com', }, 'noattrib@example.com', { 'type' => 'private', '-content' => 'dontspam@psychogenic.com', } ], 'address' => '1234 Skid Row, Irvine, CA 92618', }, { 'id' => '007', 'type' => 'SuperSpy', 'name' => 'James Bond', 'email' => 'mi5@london.uk', 'address' => 'Wherever he is needed most', }, { 'id' => '006', 'number' => 6, 'name' => 'Number 6', 'email' => 'prisoner@aol.com', 'comment' => 'I am not a man, I am a free number', 'address' => '6 Prison Island Road, Prison Island, Somewhere', } ], }; $numchildren = $miniXML->fromHash($newDocHash, $attribs); ok($numchildren, 3); my $xmlString = qq| mi5\@london.uk James Bond
Wherever he is needed most
SuperSpy
I am not a man, I am a free number Number 6 prisoner\@aol.com
6 Prison Island Road, Prison Island, Somewhere
|; $miniXML->init(); $numchildren = $miniXML->parse($xmlString); ok($numchildren, 1); my $toHash = $miniXML->toHash(); # print STDERR Dumper($toHash); ok($toHash->{'people'}->{'person'}->[0]->{'id'}, '007'); ok($toHash->{'people'}->{'person'}->[1]->{'id'}, '006'); my $options = { 'attributes' => { 'spy' => 'id', 'email' => 'type', 'friend' => ['name', 'age'], } }; my $h = { 'spy' => { 'id' => '007', 'type' => 'SuperSpy', 'name' => 'James Bond', 'email' => { 'type' => 'private', '-content' => 'mi5@london.uk', }, 'address' => { 'type' => 'residential', '-content' => 'Wherever he is needed most', }, 'friend' => [ { 'name' => 'claudia', 'age' => 25, 'type' => 'close', }, { 'name' => 'monneypenny', 'age' => '40something', 'type' => 'tease', }, { 'name' => 'Q', 'age' => '10E4', 'type' => 'pain', } ], }, }; $numchildren = $miniXML->fromHash($h, $options); ok($numchildren, 1); my $spyname = $miniXML->getElementByPath('spy/name'); ok($spyname); my $name = $spyname->getValue(); ok($name, 'James Bond'); } XML-Mini-1.38/t/09invalidxml.t0000644000076400007670000000066310751251602015770 0ustar malcalypsecorbause Test; use strict; $^W = 1; # play nice with old perl BEGIN { plan tests=> 2 } use FileHandle; require XML::Mini::Document; use strict; my $textBalancedUnavail; my $sample = './t/sample/invalid.xml'; { $XML::Mini::DieOnBadXML = 0; ok($XML::Mini::DieOnBadXML, 0); # dumb thing to avoid a superfluous warning my $miniXML = XML::Mini::Document->new(); my $numchildren = $miniXML->fromFile($sample); ok($numchildren, 0); } XML-Mini-1.38/t/sample/0002755000076400007670000000000010751724614014551 5ustar malcalypsecorbaXML-Mini-1.38/t/sample/voicexmlbbs.vxml0000644000076400007670000001615210751243735020001 0ustar malcalypsecorba
XML-Mini-1.38/t/sample/invalid.xml0000644000076400007670000000006010751244177016714 0ustar malcalypsecorba XML-Mini-1.38/t/sample/xnested.xml0000644000076400007670000000125110524222226016730 0ustar malcalypsecorba 12 Egypt 0 -31 XML-Mini-1.38/t/sample/vocpboxes.xml0000644000076400007670000000726310751720446017310 0ustar malcalypsecorba root.rmd There are lots of test tags here, it would seem... root 0=998,1=011,2=012 menu_en.rmd pat 0=998,1=101,2=556,3=201,4=301,9=001 menu_fr.rmd pat 0=998,1=557,2=102,3=202,4=302,9=001 mail pat someuser@psychogenic.com generic_en.rmd 100 pat_fr.rmd 100 system/pager.rmd pager root someuser@psychogenic.com generic_en.rmd group 100,555 generic_fr.rmd group 100,555 script root 001 raw tts generic_en.rmd group 100,555 generic_fr.rmd group 100,555 faxondemand /usr/local/vocp/faxtest.g3 script pat 001 exit mail fireball otheruser@psychogenic.com helene_en.rmd fireball 555 helene_fr.rmd fireball 555 command root text output ip.pl none output ip.pl eth0 hohohohoho 3rdparam none tts motd.pl raw output echo.pl command root none output date.pl none exit date.pl system/goodbye.rmd exit XML-Mini-1.38/t/04crossnested.t0000644000076400007670000000156310751251651016154 0ustar malcalypsecorbause Test; use strict; $^W = 1; # play nice with old perl BEGIN { plan tests=> 3 } use FileHandle; require XML::Mini::Document; use strict; my $textBalancedUnavail; my $sample = './t/sample/xnested.xml'; { eval "use Text::Balanced"; if ($@) { $textBalancedUnavail = 'Text::Balanced unavailable. Cross-nested XML *will* fail.'; } # Text::Balanced is unavailable $XML::Mini::AutoEscapeEntities = 0; ok($XML::Mini::AutoEscapeEntities, 0); # avoid warning my $miniXML = XML::Mini::Document->new(); my $numchildren = $miniXML->fromFile($sample); skip($textBalancedUnavail, $numchildren, 4); my $inputFileHandle = FileHandle->new(); unless ($inputFileHandle->open("<$sample")) { ok(0); } my $sampleFile = join('', $inputFileHandle->getlines()); $inputFileHandle->close(); my $xmlOut = $miniXML->toString(); skip($textBalancedUnavail, $sampleFile, $xmlOut); } XML-Mini-1.38/INSTALL0000755000076400007670000000156310751724553014066 0ustar malcalypsecorba#!/bin/sh # XML::Mini # # XML::Mini perl extension, XML parser/generator package. # Copyright (C) 2002-2008 Patrick Deegan, Psychogenic INC # All rights reserved # http://minixml.psychogenic.com # # See the LICENSE file for details on terms/conditions of use. # # Installation. The usual procedure will function nicely : perl Makefile.PL make make test make install # # but note that, since XML::Mini is 100% perl, you could probably just: # # - Select a location and create an XML directory: # # $ mkdir /path/to/install/XML # # - Move the modules to the install location # # $ mv Mini Mini.pm /path/to/install/XML # # - Then specify the location of the library in your code # # #!/usr/bin/perl # # use lib '/path/to/install'; # use XML::Mini; # # # ... # # # Regards, # Pat Deegan # XML-Mini-1.38/lib/0002755000076400007670000000000010751724614013573 5ustar malcalypsecorbaXML-Mini-1.38/lib/XML/0002755000076400007670000000000010751724614014233 5ustar malcalypsecorbaXML-Mini-1.38/lib/XML/Mini.pm0000644000076400007670000001635710751723725015501 0ustar malcalypsecorbapackage XML::Mini; use strict; $^W = 1; use vars qw ( $AutoEscapeEntities $AutoSetParent $AvoidLoops $CaseSensitive $Debug $IgnoreWhitespaces $NoWhiteSpaces $CheckXMLBeforeParsing $DieOnBadXML $VERSION $IgnoreDeepRecursionWarnings ); $VERSION = '1.38'; $AvoidLoops = 0; $AutoEscapeEntities = 1; $Debug = 0; $IgnoreWhitespaces = 1; $CaseSensitive = 0; $AutoSetParent = 0; $NoWhiteSpaces = -999; $CheckXMLBeforeParsing = 1; $DieOnBadXML = 1; $IgnoreDeepRecursionWarnings = 1; sub Log { my $class = shift; print STDERR "XML::Mini LOG MESSAGE:" ; print STDERR join(" ", @_) . "\n"; } sub Error { my $class = shift; my $errMsg = "XML::Mini Error MESSAGE:" . join(" ", @_) . "\n"; print STDERR $errMsg; die $errMsg; } sub escapeEntities { my $class = shift; my $toencode = shift; return undef unless (defined $toencode); $toencode=~s/&/&/g; $toencode=~s/\"/"/g; $toencode=~s/>/>/g; $toencode=~s/new(); # init the doc from an XML string $xmlDoc->parse($XMLString); # You may use the toHash() method to automatically # convert the XML into a hash reference my $xmlHash = $xmlDoc->toHash(); print Dumper($xmlHash); # You can also manipulate the elements like directly, like this: # Fetch the ROOT element for the document # (an instance of XML::Mini::Element) my $xmlRoot = $xmlDoc->getRoot(); # play with the element and its children # ... my $topLevelChildren = $xmlRoot->getAllChildren(); foreach my $childElement (@{$topLevelChildren}) { # ... } ###### CREATING XML ####### # Create a new document from scratch my $newDoc = XML::Mini::Document->new(); # This can be done easily by using a hash: my $h = { 'spy' => { 'id' => '007', 'type' => 'SuperSpy', 'name' => 'James Bond', 'email' => 'mi5@london.uk', 'address' => 'Wherever he is needed most', }, }; $newDoc->fromHash($h); # Or new XML can also be created by manipulating #elements directly: my $newDocRoot = $newDoc->getRoot(); # create the header my $xmlHeader = $newDocRoot->header('xml'); # add the version $xmlHeader->attribute('version', '1.0'); my $person = $newDocRoot->createChild('person'); my $name = $person->createChild('name'); $name->createChild('first')->text('John'); $name->createChild('last')->text('Doe'); my $eyes = $person->createChild('eyes'); $eyes->attribute('color', 'blue'); $eyes->attribute('number', 2); # output the document print $newDoc->toString(); This example would output : John Doe =head1 DESCRIPTION XML::Mini is a set of Perl classes that allow you to access XML data and create valid XML output with a tree-based hierarchy of elements. The MiniXML API has both Perl and PHP implementations. It provides an easy, object-oriented interface for manipulating XML documents and their elements. It is currently being used to send requests and understand responses from remote servers in Perl or PHP applications. An XML::Mini based parser is now being tested within the RPC::XML framework. XML::Mini does not require any external libraries or modules and is pure Perl. If available, XML::Mini will use the Text::Balanced module in order to escape limitations of the regex-only approach (eg "cross-nested" tag parsing). The Mini.pm module includes a number of variables you may use to tweak XML::Mini's behavior. These include: $XML::Mini::AutoEscapeEntities - when greater than 0, the values set for nodes are automatically escaped, thus $element->text('4 is > 3') will set the contents of the appended node to '4 is > 3'. Default setting is 1. $XML::Mini::IgnoreWhitespaces - when greater than 0, extraneous whitespaces will be ignored (maily useful when parsing). Thus Hello There will be parsed as containing a text node with contents 'Hello There' instead of ' Hello There '. Default setting is 1. $XML::Mini::CaseSensitive - when greater than 0, element names are treated as case sensitive. Thus, $element->getElement('subelement') and $element->getElement('SubElement') will be equivalent. Defaults to 0. =head1 Class methods =head2 escapeEntites TOENCODE This method returns ToENCODE with HTML sensitive values (eg '<', '>', '"', etc) HTML encoded. =cut =head2 Log MESSAGE Logs the message to STDERR =head2 Error MESSAGE Logs MESSAGE and exits the program, calling exit() =head2 ignoreDeepRecursionWarning XML::Mini uses deep recursion on big XML docs, this is normal. But the warnings are a pain. $XML::Mini::IgnoreDeepRecursionWarnings is set to TRUE by default, and ignoreDeepRecursionWarning() is called by XML::Mini::Document if it is set. To bypass this behavior, use XML::Mini; $XML::Mini::IgnoreDeepRecursionWarnings = 0; use XML::Mini::Document; # ... =head1 AUTHOR Copyright (C) 2002-2008 Patrick Deegan, Psychogenic Inc. Programs that use this code are bound to the terms and conditions of the GNU GPL (see the LICENSE file). If you wish to include these modules in non-GPL code, you need prior written authorisation from the authors. This library is released under the terms of the GNU GPL version 3, making it available only for free programs ("free" here being used in the sense of the GPL, see http://www.gnu.org for more details). Anyone wishing to use this library within a proprietary or otherwise non-GPLed program MUST contact psychogenic.com to acquire a distinct license for their application. This approach encourages the use of free software while allowing for proprietary solutions that support further development. =head2 LICENSE XML::Mini::Element module, part of the XML::Mini XML parser/generator package. Copyright (C) 2002-2008 Patrick Deegan All rights reserved XML::Mini is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XML::Mini is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XML::Mini. If not, see . =head1 SEE ALSO XML::Mini::Document, XML::Mini::Element http://minixml.psychogenic.com =cut XML-Mini-1.38/lib/XML/Mini/0002755000076400007670000000000010751724614015127 5ustar malcalypsecorbaXML-Mini-1.38/lib/XML/Mini/Node.pm0000644000076400007670000001244010751724002016340 0ustar malcalypsecorbapackage XML::Mini::Node; use strict; $^W = 1; use XML::Mini; use XML::Mini::TreeComponent; use vars qw ( $VERSION @ISA ); push @ISA, qw ( XML::Mini::TreeComponent ); $VERSION = '1.36'; sub new { my $class = shift; my $value = shift; my $self = {}; bless $self, ref $class || $class; if (defined ($value)) { if ($XML::Mini::IgnoreWhitespaces) { $value =~ s/^\s*(.*?)\s*$/$1/; } if ($XML::Mini::AutoEscapeEntities) { $value = XML::Mini->escapeEntities($value); } if ($XML::Mini::Debug) { XML::Mini->Log("Setting value of node to '$value'"); } $self->{'_contents'} = $value; } return $self; } sub getValue { my $self = shift; if ($XML::Mini::Debug) { XML::Mini->Log("Returning value of node as '" . $self->{'_contents'} . "'"); } return $self->{'_contents'}; } sub text { my $self = shift; my $setToPrim = shift; my $setToAlt = shift; my $setTo = defined ($setToPrim) ? $setToPrim : $setToAlt; if (defined ($setTo)) { if ($XML::Mini::IgnoreWhitespaces) { $setTo =~ s/^\s*(.*?)\s*$/$1/; } if ($XML::Mini::AutoEscapeEntities) { $setTo = XML::Mini->escapeEntities($setTo); } if ($XML::Mini::Debug) { XML::Mini->Log("Setting text of node to '$setTo'"); } $self->{'_contents'} = $setTo; } return $self->{'_contents'}; } sub numeric { my $self = shift; my $setToPrim = shift; my $setToAlt = shift; my $setTo = defined ($setToPrim) ? $setToPrim : $setToAlt; if (defined $setTo) { if ($setTo =~ m/^\s*[Ee\d\.\+-]+\s*$/) { return $self->text($setTo); } else { XML::Mini->Error("Node::numeric() Must pass a NUMERIC value to set ($setTo)"); } } return $self->{'_contents'}; } sub toString { my $self = shift; my $depth = shift; if ($XML::Mini::Debug) { XML::Mini->Log("Node::toString() call with depth $depth"); } if ($depth == $XML::Mini::NoWhiteSpaces) { return $self->toStringNoWhiteSpaces(); } #my $spaces = $self->_spaceStr($depth); #my $retStr; = $spaces; my $retStr = $self->{'_contents'}; #$retStr =~ s/\n\s*/\n$spaces/smg; return $retStr; } sub toStringNoWhiteSpaces { my $self = shift; my $retStr = "$self->{'_contents'}"; return $retStr; } 1; __END__ =head1 class XML::Mini::Node Nodes are used as atomic containers for numerical and text data and act as leaves in the XML tree. They have no name or children. They always exist as children of XML::MiniElements. For example, this text is bold Would be represented as a XML::MiniElement named 'B' with a single child, a Node object which contains the string 'this text is bold'. a Node has - a parent - data (text OR numeric) =head2 getValue Returns the text or numeric value of this Node. =head2 text [SETTO [SETTOALT]] The text() method is used to get or set text data for this node. If SETTO is passed, the node's content is set to the SETTO string. If the optional SETTOALT is passed and SETTO is false, the node's value is set to SETTOALT. Returns this node's text, if set or NULL =head2 numeric [SETTO [SETTOALT]] The numeric() method is used to get or set numerical data for this node. If SETTO is passed, the node's content is set to the SETTO string. If the optional SETTOALT is passed and SETTO is NULL, the node's value is set to SETTOALT. Returns this node's text, if set or NULL =head2 toString [DEPTH] Returns this node's contents as a string. If the special DEPTH $XML::Mini::NoWhiteSpaces is passed, no whitespaces will be inserted. =head1 AUTHOR Copyright (C) 2002-2008 Patrick Deegan, Psychogenic Inc. Programs that use this code are bound to the terms and conditions of the GNU GPL (see the LICENSE file). If you wish to include these modules in non-GPL code, you need prior written authorisation from the authors. This library is released under the terms of the GNU GPL version 3, making it available only for free programs ("free" here being used in the sense of the GPL, see http://www.gnu.org for more details). Anyone wishing to use this library within a proprietary or otherwise non-GPLed program MUST contact psychogenic.com to acquire a distinct license for their application. This approach encourages the use of free software while allowing for proprietary solutions that support further development. =head2 LICENSE XML::Mini::Node module, part of the XML::Mini XML parser/generator package. Copyright (C) 2002-2008 Patrick Deegan All rights reserved XML::Mini is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XML::Mini is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XML::Mini. If not, see . Official XML::Mini site: http://minixml.psychogenic.com Contact page for author available on http://www.psychogenic.com/ =cut XML-Mini-1.38/lib/XML/Mini/TreeComponent.pm0000644000076400007670000001020610751724025020240 0ustar malcalypsecorbapackage XML::Mini::TreeComponent; use strict; $^W = 1; use Data::Dumper; use XML::Mini; use vars qw ( $VERSION ); $VERSION = '1.28'; sub new { my $class = shift; my $self = {}; bless $self, ref $class || $class; return $self; } sub name { my $self = shift; my $setTo = shift; # optionally set return undef; } sub getElement { my $self = shift; my $name = shift; return undef; } sub getValue { my $self = shift; return undef; } sub parent { my $self = shift; my $newParent = shift; # optionally set if ($newParent) { my $ownType = ref $self; my $type = ref $newParent; if ($type && $type =~ /^$ownType/) { $self->{'_parent'} = $newParent; } else { return XML::Mini->Error("XML::MiniTreeComponent::parent(): Must pass an instance derived from " . "XML::MiniTreeComponent to set."); } } return $self->{'_parent'}; } sub toString { my $self = shift; my $depth = shift || 0; return undef; } sub dump { my $self = shift; return Dumper($self); } sub _spaceStr { my $self = shift; my $numSpaces = shift; my $retStr = ''; if ($numSpaces) { $retStr = ' ' x $numSpaces; } return $retStr; } 1; __END__ =head1 NAME XML::Mini::TreeComponent - Perl implementation of the XML::Mini TreeComponent API. =head1 SYNOPSIS Don't use this class - only presents an interface for other derived classes. =head1 DESCRIPTION This class is only to be used as a base class for others. It presents the minimal interface we can expect from any component in the XML hierarchy. All methods of this base class simply return NULL except a little default functionality included in the parent() method. Warning: This class is not to be instatiated. Derive and override. =head2 parent [NEWPARENT] The parent() method is used to get/set the element's parent. If the NEWPARENT parameter is passed, sets the parent to NEWPARENT (NEWPARENT must be an instance of a class derived from XML::MiniTreeComponent) Returns a reference to the parent XML::MiniTreeComponent if set, NULL otherwise. =head2 toString [DEPTH] Return a stringified version of the XML representing this component and all sub-components =head2 dump Debugging aid, dump returns a nicely formatted dump of the current structure of the XML::Mini::TreeComponent-derived object. =head1 AUTHOR Copyright (C) 2002-2008 Patrick Deegan, Psychogenic Inc. Programs that use this code are bound to the terms and conditions of the GNU GPL (see the LICENSE file). If you wish to include these modules in non-GPL code, you need prior written authorisation from the authors. This library is released under the terms of the GNU GPL version 3, making it available only for free programs ("free" here being used in the sense of the GPL, see http://www.gnu.org for more details). Anyone wishing to use this library within a proprietary or otherwise non-GPLed program MUST contact psychogenic.com to acquire a distinct license for their application. This approach encourages the use of free software while allowing for proprietary solutions that support further development. =head2 LICENSE XML::Mini::TreeComponent module, part of the XML::Mini XML parser/generator package. Copyright (C) 2002-2008 Patrick Deegan All rights reserved XML::Mini is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XML::Mini is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XML::Mini. If not, see . Official XML::Mini site: http://minixml.psychogenic.com Contact page for author available on http://www.psychogenic.com/ =head1 SEE ALSO XML::Mini, XML::Mini::Document, XML::Mini::Element http://minixml.psychogenic.com =cut XML-Mini-1.38/lib/XML/Mini/Element.pm0000644000076400007670000010120410751723736017056 0ustar malcalypsecorbapackage XML::Mini::Element; use strict; $^W = 1; use XML::Mini; use XML::Mini::TreeComponent; use XML::Mini::Element::Comment; use XML::Mini::Element::DocType; use XML::Mini::Element::Entity; use XML::Mini::Element::CData; use vars qw ( $VERSION @ISA ); push @ISA, qw ( XML::Mini::TreeComponent ); $VERSION = '1.38'; sub new { my $class = shift; my $name = shift; my $self = {}; bless $self, ref $class || $class; $self->{'_attributes'} = {}; $self->{'_numChildren'} = 0; $self->{'_numElementChildren'} = 0; $self->{'_children'} = []; $self->{'_avoidLoops'} = $XML::Mini::AvoidLoops; if ($name) { $self->name($name); } else { return XML::Mini->Error("Must pass a name to create a new Element."); } return $self; } sub name { my $self = shift; my $name = shift; if (defined $name) { $self->{'_name'} = $name; } return $self->{'_name'}; } sub attribute { my $self = shift; my $name = shift || return undef; my $primValue = shift; my $altValue = shift; my $value = (defined $primValue) ? $primValue : $altValue; if (defined $value) { $self->{'_attributes'}->{$name} = $value; } else { $self->{'_attributes'}->{$name} = '' unless (defined $self->{'_attributes'}->{$name}); } if (defined $self->{'_attributes'}->{$name}) { return $self->{'_attributes'}->{$name}; } return undef; } sub text { my $self = shift; my $primValue = shift; my $altValue = shift; my $setTo = (defined $primValue) ? $primValue : $altValue; if (defined $setTo) { $self->createNode($setTo); } my @contents; foreach my $child (@{$self->{'_children'}}) { my $value = $child->getValue(); if (defined $value) { push @contents, $value; } } if (scalar @contents) { my $retStr = join(' ', @contents); return $retStr; } return undef; } sub numeric { my $self = shift; my $primValue = shift; my $altValue = shift; my $setTo = (defined $primValue) ? $primValue : $altValue; if (defined $setTo) { return XML::Mini->Error("Must pass a NUMERIC value to Element::numeric() to set ($setTo)") unless ($setTo =~ m/^\s*[Ee\d\.\+-]+\s*$/); $self->text($setTo); } my @contents; foreach my $child (@{$self->{'_children'}}) { my $value = $child->getValue(); if (defined $value) { push @contents, $value if ($value =~ /^\s*[Ee\d\.\+-]+\s*$/); } } if (scalar @contents) { my $retStr = join(' ', @contents); return $retStr; } return undef; } sub comment { my $self = shift; my $contents = shift; my $newEl = XML::Mini::Element::Comment->new(); $newEl->text($contents); $self->appendChild($newEl); return $newEl; } sub header { my $self = shift; my $name = shift; my $attribs = shift; # optional unless (defined $name) { return XML::Mini->Error("XML::Mini::Element::header() must pass a NAME to create a new header"); } my $newElement = XML::Mini::Element::Header->new($name); $self->appendChild($newElement); return $newElement; } sub docType { my $self = shift; my $definition = shift; my $newElement = XML::Mini::Element::DocType->new($definition); $self->appendChild($newElement); return $newElement; } sub entity { my $self = shift; my $name = shift; my $value = shift; my $newElement = XML::Mini::Element::Entity->new($name, $value); $self->appendChild($newElement); return $newElement; } sub cdata { my $self = shift; my $contents = shift; my $newElement = XML::Mini::Element::CData->new($contents); $self->appendChild($newElement); return $newElement; } # Note: the seperator parameter remains officially undocumented # since I'm not sure it will remain part of the API sub getValue { my $self = shift; my $seperator = shift || ' '; my @valArray; my $retStr = ''; foreach my $child ( @{$self->{'_children'}}) { my $value = $child->getValue(); if (defined $value) { push @valArray , $value; } } if (scalar @valArray) { $retStr = join($seperator, @valArray); } return $retStr; } sub getElement { my $self = shift; my $name = shift; my $elementNumber = shift || 1; return XML::Mini->Error("Element::getElement() Must Pass Element name.") unless defined ($name); if ($XML::Mini::Debug) { XML::Mini->Log("Element::getElement() called for $name on " . $self->{'_name'} ); } ########## getElement needs to search the calling element's children ONLY ########## or else it is impossible to retrieve the nested element of the same name: ########## ########## ########## The second nested element is inaccessible if we return $self... ########## ########## #if ($XML::Mini::CaseSensitive) #{ #return $self if ($self->{'_name'} =~ m/^$name$/); #} else { #return $self if ($self->{'_name'} =~ m/^$name$/i); #} return undef unless $self->{'_numChildren'}; my $foundCount = 0; #* Try each child (immediate children take priority) * for (my $i = 0; $i < $self->{'_numChildren'}; $i++) { my $childname = $self->{'_children'}->[$i]->name(); if ($childname) { if ($XML::Mini::CaseSensitive) { if ($name =~ m/^$childname$/) { $foundCount++; return $self->{'_children'}->[$i] if ($foundCount == $elementNumber); } } else { if ($name =~ m/^$childname$/i) { $foundCount++; return $self->{'_children'}->[$i] if ($foundCount == $elementNumber); } } } #/* end if child has a name */ } #/* end loop over all my children */ #/* Now, Use beautiful recursion, daniel san */ for (my $i = 0; $i < $self->{'_numChildren'}; $i++) { my $theelement = $self->{'_children'}->[$i]->getElement($name, $elementNumber); if ($theelement) { XML::Mini->Log("Element::getElement() returning element " . $theelement->name()) if ($XML::Mini::Debug); return $theelement; } } #/* Not found */ return undef; } sub getElementByPath { my $self = shift; my $path = shift || return undef; my @elementNumbers = @_; my @names = split ("/", $path); my $element = $self; my $position = 0; foreach my $elementName (@names) { next unless ($elementName); if ($element) #/* Make sure we didn't hit a dead end */ { #/* Ask this element to get the next child in path */ $element = $element->getElement($elementName, $elementNumbers[$position++]); } } return $element; } #/* end method getElementByPath */ sub numChildren { my $self = shift; my $named = shift; # optionally only count elements named 'named' unless (defined $named) { return $self->{'_numElementChildren'}; } my $allkids = $self->getAllChildren($named); return scalar @{$allkids}; } sub getAllChildren { my $self = shift; my $name = shift; # optionally only children with this name my @returnChildren; for (my $i=0; $i < $self->{'_numChildren'}; $i++) { if ($self->isElement($self->{'_children'}->[$i])) { my $childName = $self->{'_children'}->[$i]->name(); # return only Element and derivatives children if (defined $name) { if ($XML::Mini::CaseSensitive) { push @returnChildren, $self->{'_children'}->[$i] if ($name =~ /^$childName$/); } else { # case insensitive push @returnChildren, $self->{'_children'}->[$i] if ($name =~ /^$childName$/i); } } else { # no name set, all children returned push @returnChildren, $self->{'_children'}->[$i]; } # end if name } # end if element } # end loop over all children return \@returnChildren; } sub isElement { my $self = shift; my $element = shift || $self; my $type = ref $element; return undef unless $type; return 0 unless ($type =~ /^XML::Mini::Element/); return 1; } sub isNode { my $self = shift; my $element = shift || $self; my $type = ref $element; return undef unless $type; return 0 unless ($type =~ /^XML::Mini::Node/); return 1; } sub insertChild { my $self = shift; my $child = shift; my $idx = shift || 0; $self->_validateChild($child); if ($self->{'_avoidLoops'} || $XML::Mini::AutoSetParent) { if ($self->{'_parent'} == $child) { my $childName = $child->name(); return XML::Mini->Error("Element::insertChild() Tryng to append parent $childName as child of " . $self->name()); } $child->parent($self); } my $nextIdx = $self->{'_numChildren'}; my $lastIdx = $nextIdx - 1; if ($idx > $lastIdx) { if ($idx > $nextIdx) { $idx = $lastIdx + 1; } $self->{'_children'}->[$idx] = $child; $self->{'_numChildren'}++; $self->{'_numElementChildren'}++ if ($self->isElement($child)); } elsif ($idx >= 0) { my @removed = splice(@{$self->{'_children'}}, $idx); push @{$self->{'_children'}}, ($child, @removed); $self->{'_numChildren'}++; $self->{'_numElementChildren'}++ if ($self->isElement($child)); } else { my $revIdx = (-1 * $idx) % $self->{'_numChildren'}; my $newIdx = $self->{'_numChildren'} - $revIdx; if ($newIdx < 0) { return XML::Mini->Error("Element::insertChild() Ended up with a negative index? ($newIdx)"); } return $self->insertChild($child, $newIdx); } return $child; } sub appendChild { my $self = shift; my $child = shift; $self->_validateChild($child); if ($self->{'_avoidLoops'} || $XML::Mini::AutoSetParent) { if ($self->{'_parent'} == $child) { my $childName = $child->name(); return XML::Mini->Error("Element::appendChild() Tryng to append parent $childName as child of " . $self->name()); } $child->parent($self); } $self->{'_numElementChildren'}++; #Note that we're addind a Element child my $idx = $self->{'_numChildren'}++; $self->{'_children'}->[$idx] = $child; return $self->{'_children'}->[$idx]; } sub prependChild { my $self = shift; my $child = shift; $self->_validateChild($child); if ($self->{'_avoidLoops'} || $XML::Mini::AutoSetParent) { if ($self->{'_parent'} == $child) { my $childName = $child->name(); return XML::Mini->Error("Element::appendChild() Tryng to append parent $childName as child of " . $self->name()); } $child->parent($self); } $self->{'_numElementChildren'}++; #Note that we're addind a Element child my $idx = $self->{'_numChildren'}++; unshift(@{$self->{'_children'}}, $child); return $self->{'_children'}->[0]; } sub createChild { my $self = shift; my $name = shift; my $value = shift; # optionally fill child with unless (defined $name) { return XML::Mini->Error("Element::createChild() Must pass a NAME to createChild."); } my $child = XML::Mini::Element->new($name); $child = $self->appendChild($child); if (defined $value) { if ($value =~ m/^\s*[Ee\d\.\+-]+\s*$/) { $child->numeric($value); } else { $child->text($value); } } $child->avoidLoops($self->{'_avoidLoops'}); return $child; } sub _validateChild { my $self = shift; my $child = shift; return XML::Mini->Error("Element:_validateChild() need to pass a non-NULL Element child") unless (defined $child); return XML::Mini->Error("Element::_validateChild() must pass an Element object to appendChild.") unless ($self->isElement($child)); my $childName = $child->name(); return XML::Mini->Error("Element::_validateChild() children must be named") unless (defined $childName); if ($child == $self) { return XML::Mini->Error("Element::_validateChild() Trying to append self as own child!"); } elsif ( $self->{'_avoidLoops'} && $child->parent()) { return XML::Mini->Error("Element::_validateChild() Trying to append a child ($childName) that already has a parent set " . "while avoidLoops is on - aborting"); } return 1; } sub removeChild { my $self = shift; my $child = shift; unless (defined $child) { XML::Mini->Log("Element::removeChild() called without an ELEMENT parameter."); return undef; } unless ($self->{'_numChildren'}) { return XML::Mini->Error("Element::removeChild() called for element without any children."); } my $childType = ref $child; unless ($childType && $childType =~ /XML::Mini::/) { # name of the child... # try to find it... my $el = $self->getElement($child); return XML::Mini->Error("Element::removeChild() called with element _name_ $child, but could not find any such element") unless ($el); $child = $el; } my $foundChild; my $idx = 0; while ($idx < $self->{'_numChildren'} && ! $foundChild) { if ($self->{'_children'}->[$idx] == $child) { $foundChild = $self->{'_children'}->[$idx]; } else { $idx++; } } unless ($foundChild) { XML::Mini->Log("Element::removeChild() No matching child found.") if ($XML::Mini::Debug); return undef; } splice @{$self->{'_children'}}, $idx, 1; $self->{'_numChildren'}--; if ($foundChild->isElement()) { $self->{'_numElementChildren'}--; } delete $foundChild->{'_parent'} ; return $foundChild; } sub removeAllChildren { my $self = shift; return undef unless ($self->{'_numChildren'}); my $retList = $self->{'_children'}; delete $self->{'_children'}; $self->{'_numElementChildren'} = 0; $self->{'_numChildren'} = 0; foreach my $child (@{$retList}) { delete $child->{'_parent'}; } delete $self->{'_children'}; $self->{'children'} = []; return $retList; } sub remove { my $self = shift; my $parent = $self->parent(); unless ($parent) { XML::Mini->Log("XML::Mini::Element::remove() called for element with no parent set. Aborting."); return undef; } my $removed = $parent->removeChild($self); return $removed; } sub parent { my $self = shift; my $parent = shift; # optionally set if (defined $parent) { return XML::Mini->Error("Element::parent(): Must pass an instance of Element to set.") unless ($self->isElement($parent)); $self->{'_parent'} = $parent; } return $self->{'_parent'}; } sub avoidLoops { my $self = shift; my $setTo = shift; # optionally set if (defined $setTo) { $self->{'_avoidLoops'} = $setTo; } return $self->{'_avoidLoops'}; } sub toStructure { my $self = shift; my $retHash = {}; my $contents = ""; my $numAdded = 0; if ($self->{'_attributes'}) { while (my ($attname, $attvalue) = each %{$self->{'_attributes'}}) { $retHash->{$attname} = $attvalue; $numAdded++; } } my $numChildren = $self->{'_numChildren'} || 0; for (my $i=0; $i < $numChildren ; $i++) { my $thisChild = $self->{'_children'}->[$i]; if ($self->isElement($thisChild)) { my $name = $thisChild->name(); my $struct = $thisChild->toStructure(); my $existing = $retHash->{$name}; if ($existing) { my $existingType = ref $existing || ""; if ($existingType eq 'ARRAY') { push @{$existing}, $struct; } else { my $arrayRef = [$existing, $struct]; $retHash->{$name} = $arrayRef; } } else { $retHash->{$name} = $struct; } $numAdded++; } else { $contents .= $thisChild->getValue(); } } if ($numAdded) { if (length($contents)) { $retHash->{'-content'} = $contents; } return $retHash; } else { return $contents; } } sub toString { my $self = shift; my $depth = shift || 0; if ($depth == $XML::Mini::NoWhiteSpaces) { return $self->toStringNoWhiteSpaces(); } my $retString; my $attribString = ''; my $elementName = $self->{'_name'}; my $spaces = $self->_spaceStr($depth); foreach my $atName (sort keys %{$self->{'_attributes'}}) { $attribString .= qq|$atName="$self->{'_attributes'}->{$atName}" |; } $retString = "$spaces<$elementName"; if ($attribString) { $attribString =~ s/\s*$//; $retString .= " $attribString"; } if (! $self->{'_numChildren'}) { $retString .= " />\n"; return $retString; } # Else, we do have kids - sub element or nodes my $allChildrenAreNodes = 1; my $i=0; while ($allChildrenAreNodes && $i < $self->{'_numChildren'}) { $allChildrenAreNodes = 0 unless ($self->isNode($self->{'_children'}->[$i])); $i++; } $retString .= ">"; $retString .= "\n" unless ($allChildrenAreNodes); my $nextDepth = $depth + 1; for($i=0; $i < $self->{'_numChildren'}; $i++) { my $newStr = $self->{'_children'}->[$i]->toString($nextDepth); if (defined $newStr) { if ( ! ($allChildrenAreNodes || $newStr =~ m|\n$|) ) { $newStr .= "\n"; } $retString .= $newStr; } # end if newStr returned } # end loop over all children $retString .= "$spaces" unless ($allChildrenAreNodes); $retString .= "\n"; return $retString; } sub toStringNoWhiteSpaces { my $self = shift; my $retString; my $attribString = ''; my $elementName = $self->{'_name'}; while (my ($atName, $atVal) = each %{$self->{'_attributes'}}) { $attribString .= qq|$atName="$atVal" |; } $retString = "<$elementName"; if ($attribString) { $attribString =~ s/\s*$//; $retString .= " $attribString"; } if (! $self->{'_numChildren'}) { $retString .= '/>'; return $retString; } # Else, we do have kids - sub element or nodes $retString .= '>'; for(my $i=0; $i < $self->{'_numChildren'}; $i++) { my $newStr = $self->{'_children'}->[$i]->toStringNoWhiteSpaces(); $retString .= $newStr if (defined $newStr); } # end loop over all children $retString .= ""; return $retString; } sub createNode { my $self = shift; my $value = shift; my $newNode = XML::Mini::Node->new($value); return undef unless ($newNode); my $appendedNode = $self->appendNode($newNode); return $appendedNode; } sub appendNode { my $self = shift; my $node = shift; return XML::Mini->Error("Element::appendNode() need to pass a non-NULL XML::MiniNode.") unless (defined $node); return XML::Mini->Error("Element::appendNode() must pass a XML::MiniNode object to appendNode.") unless ($self->isNode($node)); if ($XML::Mini::AutoSetParent) { $node->parent($self); } if ($XML::Mini::Debug) { XML::Mini->Log("Appending node to " . $self->{'_name'}); } my $idx = $self->{'_numChildren'}++; $self->{'_children'}->[$idx] = $node; return $self->{'_children'}->[$idx]; } 1; __END__ =head1 NAME XML::Mini::Element - Perl implementation of the XML::Mini Element API. =head1 SYNOPSIS use XML::Mini::Document; my $xmlDoc = XML::Mini::Document->new(); # Fetch the ROOT element for the document # (an instance of XML::Mini::Element) my $xmlElement = $xmlDoc->getRoot(); # Create an tag my $xmlHeader = $xmlElement->header('xml'); # add the version to get $xmlHeader->attribute('version', '1.0'); # Create a sub element my $newChild = $xmlElement->createChild('mychild'); $newChild->text('hello mommy'); # Create an orphan element my $orphan = $xmlDoc->createElement('annie'); $orphan->attribute('hair', '#ff0000'); $orphan->text('tomorrow, tomorrow'); # Adopt the orphan $newChild->appendChild($orphan); # ... # add a child element to the front of the list $xmlElement->prependChild($otherElement); print $xmlDoc->toString(); The code above would output: hello mommy tomorrow, tomorrow =head1 DESCRIPTION Although the main handle to the xml document is the XML::Mini::Document object, much of the functionality and manipulation involves interaction with Element objects. A Element has: - a name - a list of 0 or more attributes (which have a name and a value) - a list of 0 or more children (Element or XML::MiniNode objects) - a parent (optional, only if MINIXML_AUTOSETPARENT > 0) =head2 new NAME Creates a new instance of XML::Mini::Element, with name NAME =head2 name [NEWNAME] If a NEWNAME string is passed, the Element's name is set to NEWNAME. Returns the element's name. =head2 attribute NAME [SETTO [SETTOALT]] The attribute() method is used to get and set the Element's attributes (ie the name/value pairs contained within the tag, ) If SETTO is passed, the attribute's value is set to SETTO. If the optional SETTOALT is passed and SETTO is false, the attribute's value is set to SETTOALT. This is usefull in cases when you wish to set the attribute to a default value if no SETTO is present, eg $myelement->attribute('href', $theHref, 'http://psychogenic.com') will default to 'http://psychogenic.com'. Returns the value associated with attribute NAME. =head2 text [SETTO [SETTOALT]] The text() method is used to get or append text data to this element (it is appended to the child list as a new XML::MiniNode object). If SETTO is passed, a new node is created, filled with SETTO and appended to the list of this element's children. If the optional SETTOALT is passed and SETTO is false, the new node's value is set to SETTOALT. See the attribute() method for an example use. Returns a string composed of all child XML::MiniNodes' contents. Note: all the children XML::MiniNodes' contents - including numeric nodes are included in the return string. =head2 numeric [SETTO [SETTOALT]] The numeric() method is used to get or append numeric data to this element (it is appended to the child list as a XML::MiniNode object). If SETTO is passed, a new node is created, filled with SETTO and appended to the list of this element's children. If the optional SETTOALT is passed and SETTO is false, the new node's value is set to SETTOALT. See the attribute() method for an example use. Returns a space seperated string composed all child XML::MiniNodes' numeric contents. Note: ONLY numerical contents are included from the list of child XML::MiniNodes. =head2 header NAME The header() method allows you to add a new XML::Mini::Element::Header to this element's list of children. Headers return a string for the element's toString() method. Attributes may be set using attribute(), to create headers like Valid XML documents must have at least an 'xml' header, like: Here's how you could begin creating an XML document: my $miniXMLDoc = XML::Mini::Document->new(); my $xmlRootNode = $miniXMLDoc->getRoot(); my $xmlHeader = $xmlRootNode->header('xml'); $xmlHeader->attribute('version', '1.0'); This method was added in version 1.25. =head2 comment CONTENTS The comment() method allows you to add a new XML::Mini::Element::Comment to this element's list of children. Comments will return a string when the element's toString() method is called. Returns a reference to the newly appended XML::Mini::Element::Comment =head2 docType DEFINITION Append a new element as a child of this element. Returns the appended DOCTYPE element. You will normally use the returned element to add ENTITY elements, like my $newDocType = $xmlRoot->docType('spec SYSTEM "spec.dtd"'); $newDocType->entity('doc.audience', 'public review and discussion'); =head2 entity NAME VALUE Append a new element as a child of this element. Returns the appended ENTITY element. =head2 cdata CONTENTS Append a new element as a child of this element. Returns the appended CDATA element. =head2 getValue Returns a string containing the value of all the element's child XML::MiniNodes (and all the XML::MiniNodes contained within it's child Elements, recursively). =head2 getElement NAME [POSITION] Searches the element and it's children for an element with name NAME. Returns a reference to the first Element with name NAME, if found, NULL otherwise. NOTE: The search is performed like this, returning the first element that matches: - Check this element's immediate children (in order) for a match. - Ask each immediate child (in order) to Element::getElement() (each child will then proceed similarly, checking all it's immediate children in order and then asking them to getElement()) If a numeric POSITION parameter is passed, getElement() will return the POSITIONth element of name NAME (starting at 1). Thus, on document bob jane ralph $people->getElement('person') will return the element containing the text node 'bob', while $people->getElement('person', 3) will return the element containing the text 'ralph'. =head2 getElementByPath PATH [POSITIONSARRAY] Attempts to return a reference to the (first) element at PATH where PATH is the path in the structure (relative to this element) to the requested element. For example, in the document represented by: DA42 D99983FFF ss-839uent $partRate = $xmlDocument->getElement('partRateRequest'); $accessid = $partRate->getElementByPath('vendor/accessid'); Will return what you expect (the accessid element with attributes user = "myusername" and password = "mypassword"). BUT be careful: $accessid = $partRate->getElementByPath('partList/partNum'); will return the partNum element with the value "DA42". To access other partNum elements you must either use the POSITIONSARRAY or the getAllChildren() method on the partRateRequest element. POSITIONSARRAY functions like the POSITION parameter to getElement(), but instead of specifying the position of a single element, you must indicate the position of all elements in the path. Therefore, to get the third part number element, you would use my $thirdPart = $xmlDocument->getElementByPath('partRateRequest/partList/partNum', 1, 1, 3); The additional 1,1,3 parameters indicate that you wish to retrieve the 1st partRateRequest element in the document, the 1st partList child of partRateRequest and the 3rd partNum child of the partList element (in this instance, the partNum element that contains 'ss-839uent'). Returns the Element reference if found, NULL otherwise. =head2 getAllChildren [NAME] Returns a reference to an array of all this element's Element children Note: although the Element may contain XML::MiniNodes as children, these are not part of the returned list. =head2 createChild ELEMENTNAME [VALUE] Creates a new Element instance and appends it to the list of this element's children. The new child element's name is set to ELEMENTNAME. If the optional VALUE (string or numeric) parameter is passed, the new element's text/numeric content will be set using VALUE. Returns a reference to the new child element =head2 appendChild CHILDELEMENT appendChild is used to append an existing Element object to this element's list. Returns a reference to the appended child element. NOTE: Be careful not to create loops in the hierarchy, eg $parent->appendChild($child); $child->appendChild($subChild); $subChild->appendChild($parent); If you want to be sure to avoid loops, set the MINIXML_AVOIDLOOPS define to 1 or use the avoidLoops() method (will apply to all children added with createChild()) =head2 prependChild CHILDELEMENT prependChild is used to add an existing Element object to this element's list. The added CHILDELEMENT will be prepended to the list, thus it will appear first in the XML output. Returns a reference to the prepended child element. See the note about creating loops in the above appendChild() description. =head2 insertChild CHILDELEMENT INDEX Inserts the child element at a specific location in this elements list of children. If INDEX is larger than numChildren(), the CHILDELEMENT will be added to the end of the list (same as appendChild() ). Returns the inserted child element. =head2 removeChild CHILDELEMENT Removes the element CHILDELEMENT from the list of this element's children, if it is found within this list. Returns the child element that was removed, else undef. =head2 removeAllChildren Clears the element's list of child elements. Returns an array ref of child elements that were removed. =head2 remove Removes this element from it's parent's list of children. The parent must be set for the element for this method to work - this can be done manually using the parent() method or automatically if $XML::Mini::AutoSetParent is true (set to false by default). =head2 parent NEWPARENT The parent() method is used to get/set the element's parent. If the NEWPARENT parameter is passed, sets the parent to NEWPARENT (NEWPARENT must be an instance of Element) Returns a reference to the parent Element if set, NULL otherwise. Note: This method is mainly used internally and you wouldn't normally need to use it. It get's called on element appends when $XML::Mini::AutoSetParent or $XML::Mini::AvoidLoops or avoidLoops() > 0 =head2 avoidLoops SETTO The avoidLoops() method is used to get or set the avoidLoops flag for this element. When avoidLoops is true, children with parents already set can NOT be appended to any other elements. This is overkill but it is a quick and easy way to avoid infinite loops in the heirarchy. The avoidLoops default behavior is configured with the $XML::Mini::AvoidLoops variable but can be set on individual elements (and automagically all the element's children) with the avoidLoops() method. Returns the current value of the avoidLoops flag for the element. =head2 toString [SPACEOFFSET] toString returns an XML string based on the element's attributes, and content (recursively doing the same for all children) The optional SPACEOFFSET parameter sets the number of spaces to use after newlines for elements at this level (adding 1 space per level in depth). SPACEOFFSET defaults to 0. If SPACEOFFSET is passed as $XML::Mini::NoWhiteSpaces no \n or whitespaces will be inserted in the xml string (ie it will all be on a single line with no spaces between the tags. Returns the XML string. =head2 createNode NODEVALUE Private (?) Creates a new XML::MiniNode instance and appends it to the list of this element's children. The new child node's value is set to NODEVALUE. Returns a reference to the new child node. Note: You don't need to use this method normally - it is used internally when appending text() and such data. =head2 appendNode CHILDNODE appendNode is used to append an existing XML::MiniNode object to this element's list. Returns a reference to the appended child node. Note: You don't need to use this method normally - it is used internally when appending text() and such data. =head1 AUTHOR Copyright (C) 2002-2008 Patrick Deegan, Psychogenic Inc. Programs that use this code are bound to the terms and conditions of the GNU GPL (see the LICENSE file). If you wish to include these modules in non-GPL code, you need prior written authorisation from the authors. This library is released under the terms of the GNU GPL version 3, making it available only for free programs ("free" here being used in the sense of the GPL, see http://www.gnu.org for more details). Anyone wishing to use this library within a proprietary or otherwise non-GPLed program MUST contact psychogenic.com to acquire a distinct license for their application. This approach encourages the use of free software while allowing for proprietary solutions that support further development. =head2 LICENSE XML::Mini::Element module, part of the XML::Mini XML parser/generator package. Copyright (C) 2002-2008 Patrick Deegan All rights reserved XML::Mini is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XML::Mini is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XML::Mini. If not, see . Official XML::Mini site: http://minixml.psychogenic.com Contact page for author available on http://www.psychogenic.com/ =head1 SEE ALSO XML::Mini, XML::Mini::Document http://minixml.psychogenic.com =cut XML-Mini-1.38/lib/XML/Mini/Element/0002755000076400007670000000000010751724614016520 5ustar malcalypsecorbaXML-Mini-1.38/lib/XML/Mini/Element/Entity.pm0000644000076400007670000000722210751724101020322 0ustar malcalypsecorbapackage XML::Mini::Element::Entity; use strict; $^W = 1; use XML::Mini; use XML::Mini::Element; use vars qw ( $VERSION @ISA ); $VERSION = '1.24'; push @ISA, qw ( XML::Mini::Element ); sub new { my $class = shift; my $name = shift; my $value = shift; my $self = {}; bless $self, ref $class || $class; $self->{'_attributes'} = {}; $self->{'_numChildren'} = 0; $self->{'_numElementChildren'} = 0; $self->{'_children'} = []; $self->{'_avoidLoops'} = $XML::Mini::AvoidLoops; $self->name($name); my $oldAutoEscape = $XML::Mini::AutoEscapeEntities; $XML::Mini::AutoEscapeEntities = 0; $self->createNode($value) if (defined $value); $XML::Mini::AutoEscapeEntities = $oldAutoEscape; return $self; } sub toString { my $self = shift; my $depth = shift; my $spaces; if ($depth == $XML::Mini::NoWhiteSpaces) { $spaces = ''; } else { $spaces = $self->_spaceStr($depth); } my $retString = "$spacesname(); if (! $self->{'_numChildren'}) { $retString .= ">\n"; return $retString; } my $nextDepth = ($depth == $XML::Mini::NoWhiteSpaces) ? $XML::Mini::NoWhiteSpaces : $depth + 1; $retString .= '"'; for (my $i=0; $i < $self->{'_numChildren'}; $i++) { $retString .= $self->{'_children'}->[$i]->toString($XML::Mini::NoWhiteSpaces); } $retString .= '"'; #$retString =~ s/\n//g; $retString .= " >\n"; return $retString; } sub toStringNoWhiteSpaces { my $self = shift; my $depth = shift; return $self->toString($depth); } 1; __END__ =head1 NAME XML::Mini::Element::Entity =head1 DESCRIPTION The XML::Mini::Element::Entity is used internally to represent . You shouldn't need to use it directly, see XML::Mini::Element's entity() method. =head1 AUTHOR Copyright (C) 2002-2008 Patrick Deegan, Psychogenic Inc. Programs that use this code are bound to the terms and conditions of the GNU GPL (see the LICENSE file). If you wish to include these modules in non-GPL code, you need prior written authorisation from the authors. This library is released under the terms of the GNU GPL version 3, making it available only for free programs ("free" here being used in the sense of the GPL, see http://www.gnu.org for more details). Anyone wishing to use this library within a proprietary or otherwise non-GPLed program MUST contact psychogenic.com to acquire a distinct license for their application. This approach encourages the use of free software while allowing for proprietary solutions that support further development. =head2 LICENSE XML::Mini::Element module, part of the XML::Mini XML parser/generator package. Copyright (C) 2002-2008 Patrick Deegan All rights reserved XML::Mini is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XML::Mini is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XML::Mini. If not, see . Official XML::Mini site: http://minixml.psychogenic.com Contact page for author available on http://www.psychogenic.com/ =head1 SEE ALSO XML::Mini, XML::Mini::Document, XML::Mini::Element http://minixml.psychogenic.com =cut XML-Mini-1.38/lib/XML/Mini/Element/CData.pm0000644000076400007670000000553710524222225020027 0ustar malcalypsecorbapackage XML::Mini::Element::CData; use strict; $^W = 1; use XML::Mini; use XML::Mini::Element; use vars qw ( $VERSION @ISA ); $VERSION = '1.24'; push @ISA, qw ( XML::Mini::Element ); sub new { my $class = shift; my $contents = shift; my $self = {}; bless $self, ref $class || $class; $self->{'_attributes'} = {}; $self->{'_numChildren'} = 0; $self->{'_numElementChildren'} = 0; $self->{'_children'} = []; $self->{'_avoidLoops'} = $XML::Mini::AvoidLoops; $self->name('CDATA'); my $oldAutoEscape = $XML::Mini::AutoEscapeEntities; $XML::Mini::AutoEscapeEntities = 0; $self->createNode($contents) if (defined $contents); $XML::Mini::AutoEscapeEntities = $oldAutoEscape; return $self; } sub toString { my $self = shift; my $depth = shift; my $spaces; if ($depth == $XML::Mini::NoWhiteSpaces) { $spaces = ''; } else { $spaces = $self->_spaceStr($depth); } my $retString = "$spaces{'_numChildren'}) { $retString .= "]]>\n"; return $retString; } my $nextDepth = ($depth == $XML::Mini::NoWhiteSpaces) ? $XML::Mini::NoWhiteSpaces : $depth + 1; for (my $i=0; $i < $self->{'_numChildren'}; $i++) { $retString .= $self->{'_children'}->[$i]->getValue(); } $retString .= " ]]>\n"; return $retString; } sub toStringNoWhiteSpaces { my $self = shift; my $depth = shift; return $self->toString($depth); } 1; __END__ =head1 NAME XML::Mini::Element::CData =head1 DESCRIPTION The XML::Mini::Element::CData is used internally to represent . You shouldn't need to use it directly, see XML::Mini::Element's cdata() method. =head1 AUTHOR LICENSE XML::Mini::Element::CData module, part of the XML::Mini XML parser/generator package. Copyright (C) 2002 Patrick Deegan All rights reserved This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Official XML::Mini site: http://minixml.psychogenic.com Contact page for author available at http://www.psychogenic.com/en/contact.shtml =head1 SEE ALSO XML::Mini, XML::Mini::Document, XML::Mini::Element http://minixml.psychogenic.com =cut XML-Mini-1.38/lib/XML/Mini/Element/DocType.pm0000644000076400007670000000663410751724047020434 0ustar malcalypsecorbapackage XML::Mini::Element::DocType; use strict; $^W = 1; use XML::Mini; use XML::Mini::Element; use vars qw ( $VERSION @ISA ); $VERSION = '1.38'; push @ISA, qw ( XML::Mini::Element ); sub new { my $class = shift; my $attr = shift; my $self = {}; bless $self, ref $class || $class; $self->{'_attributes'} = {}; $self->{'_numChildren'} = 0; $self->{'_numElementChildren'} = 0; $self->{'_children'} = []; $self->{'_avoidLoops'} = $XML::Mini::AvoidLoops; $self->{'_attr'} = $attr; $self->name('DOCTYPE'); return $self; } sub toString { my $self = shift; my $depth = shift; my $spaces; if ($depth == $XML::Mini::NoWhiteSpaces) { $spaces = ''; } else { $spaces = $self->_spaceStr($depth); } my $retString = "$spaces{'_attr'}; if (! $self->{'_numChildren'}) { $retString .= ">\n"; return $retString; } $retString .= " [\n"; my $nextDepth = ($depth == $XML::Mini::NoWhiteSpaces) ? $XML::Mini::NoWhiteSpaces : $depth + 1; for (my $i=0; $i < $self->{'_numChildren'}; $i++) { $retString .= $self->{'_children'}->[$i]->toString($nextDepth); } $retString .= "\n]>\n"; return $retString; } sub toStringNoWhiteSpaces { my $self = shift; my $depth = shift; return $self->toString($depth); } 1; __END__ =head1 NAME XML::Mini::Element::DocType =head1 DESCRIPTION The XML::Mini::Element::DocType is used internally to represent . You shouldn't need to use it directly, see XML::Mini::Element's docType() method. =head1 AUTHOR Copyright (C) 2002-2008 Patrick Deegan, Psychogenic Inc. Programs that use this code are bound to the terms and conditions of the GNU GPL (see the LICENSE file). If you wish to include these modules in non-GPL code, you need prior written authorisation from the authors. This library is released under the terms of the GNU GPL version 3, making it available only for free programs ("free" here being used in the sense of the GPL, see http://www.gnu.org for more details). Anyone wishing to use this library within a proprietary or otherwise non-GPLed program MUST contact psychogenic.com to acquire a distinct license for their application. This approach encourages the use of free software while allowing for proprietary solutions that support further development. =head2 LICENSE XML::Mini::Element module, part of the XML::Mini XML parser/generator package. Copyright (C) 2002-2008 Patrick Deegan All rights reserved XML::Mini is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XML::Mini is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XML::Mini. If not, see . Official XML::Mini site: http://minixml.psychogenic.com Contact page for author available on http://www.psychogenic.com/ =head1 SEE ALSO XML::Mini, XML::Mini::Document, XML::Mini::Element http://minixml.psychogenic.com =cut XML-Mini-1.38/lib/XML/Mini/Element/Header.pm0000644000076400007670000000770410751724116020251 0ustar malcalypsecorbapackage XML::Mini::Element::Header; use strict; $^W = 1; use XML::Mini; use XML::Mini::Element; use vars qw ( $VERSION @ISA ); $VERSION = '1.02'; push @ISA, qw ( XML::Mini::Element ); sub new { my $class = shift; my $name = shift || XML::Mini->Error("Must pass a NAME to XML::Mini::Element::Header::new()"); my $self = {}; bless $self, ref $class || $class; $self->{'_attributes'} = {}; $self->{'_numChildren'} = 0; $self->{'_numElementChildren'} = 0; $self->{'_children'} = []; $self->{'_avoidLoops'} = $XML::Mini::AvoidLoops; $self->name($name); return $self; } sub toString { my $self = shift; my $depth = shift; if ($depth == $XML::Mini::NoWhiteSpaces) { return $self->toStringNoWhiteSpaces(); } my $spaces = $self->_spaceStr($depth); my $retString = "$spacesname() ; my $attribString; # make sure version is always first if (exists $self->{'_attributes'}->{'version'}) { $attribString = ' version="' . $self->{'_attributes'}->{'version'} . '"'; delete $self->{'_attributes'}->{'version'}; } foreach my $atName (sort keys %{$self->{'_attributes'}}) { $attribString .= qq| $atName="$self->{'_attributes'}->{$atName}"|; } if (defined $attribString && $attribString =~ m|\S|) { $retString .= $attribString; } $retString =~ s/\s+$//; $retString .= "?>\n"; return $retString; } sub toStringNoWhiteSpaces { my $self = shift; my $retString = 'name(); my $attribString; foreach my $atName (sort keys %{$self->{'_attributes'}}) { $attribString .= qq|$atName="$self->{'_attributes'}->{$atName}" |; } if (defined $attribString && $attribString =~ m|\S|) { $retString .= $attribString; } $retString =~ s/\s+$//; $retString .= "?>"; return $retString; } 1; __END__ =head1 NAME XML::Mini::Element::Header =head1 DESCRIPTION The XML::Mini::Element::Header is used internally to represent type headers. You shouldn't need to use it directly, see XML::Mini::Element's header() method. =head1 AUTHOR Copyright (C) 2002-2008 Patrick Deegan, Psychogenic Inc. Programs that use this code are bound to the terms and conditions of the GNU GPL (see the LICENSE file). If you wish to include these modules in non-GPL code, you need prior written authorisation from the authors. This library is released under the terms of the GNU GPL version 3, making it available only for free programs ("free" here being used in the sense of the GPL, see http://www.gnu.org for more details). Anyone wishing to use this library within a proprietary or otherwise non-GPLed program MUST contact psychogenic.com to acquire a distinct license for their application. This approach encourages the use of free software while allowing for proprietary solutions that support further development. =head2 LICENSE XML::Mini::Element module, part of the XML::Mini XML parser/generator package. Copyright (C) 2002-2008 Patrick Deegan All rights reserved XML::Mini is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XML::Mini is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XML::Mini. If not, see . Official XML::Mini site: http://minixml.psychogenic.com Contact page for author available on http://www.psychogenic.com/ =head1 SEE ALSO XML::Mini, XML::Mini::Document, XML::Mini::Element http://minixml.psychogenic.com =cut XML-Mini-1.38/lib/XML/Mini/Element/Comment.pm0000644000076400007670000000704510751724065020464 0ustar malcalypsecorbapackage XML::Mini::Element::Comment; use strict; $^W = 1; use XML::Mini; use XML::Mini::Element; use vars qw ( $VERSION @ISA ); $VERSION = '1.24'; push @ISA, qw ( XML::Mini::Element ); sub new { my $class = shift; my $self = {}; bless $self, ref $class || $class; $self->{'_attributes'} = {}; $self->{'_numChildren'} = 0; $self->{'_numElementChildren'} = 0; $self->{'_children'} = []; $self->{'_avoidLoops'} = $XML::Mini::AvoidLoops; $self->name('!--'); return $self; } sub toString { my $self = shift; my $depth = shift; if ($depth == $XML::Mini::NoWhiteSpaces) { return $self->toStringNoWhiteSpaces(); } my $spaces = $self->_spaceStr($depth); my $retString = "$spaces\n"; return $retString; } my $nextDepth = $depth + 1; for (my $i=0; $i < $self->{'_numChildren'}; $i++) { $retString .= $self->{'_children'}->[$i]->toString($nextDepth); } $retString .= "\n" unless ($retString =~ m|\n$|sm); $retString .= "$spaces -->\n"; return $retString; } sub toStringNoWhiteSpaces { my $self = shift; my $retString = ''; return $retString; } for (my $i=0; $i < $self->{'_numChildren'}; $i++) { $retString .= $self->{'_children'}->[$i]->toStringNoWhiteSpaces(); } $retString .= " -->"; return $retString; } 1; __END__ =head1 NAME XML::Mini::Element::Comment =head1 DESCRIPTION The XML::Mini::Element::Comment is used internally to represent . You shouldn't need to use it directly, see XML::Mini::Element's comment() method. =head1 AUTHOR Copyright (C) 2002-2008 Patrick Deegan, Psychogenic Inc. Programs that use this code are bound to the terms and conditions of the GNU GPL (see the LICENSE file). If you wish to include these modules in non-GPL code, you need prior written authorisation from the authors. This library is released under the terms of the GNU GPL version 3, making it available only for free programs ("free" here being used in the sense of the GPL, see http://www.gnu.org for more details). Anyone wishing to use this library within a proprietary or otherwise non-GPLed program MUST contact psychogenic.com to acquire a distinct license for their application. This approach encourages the use of free software while allowing for proprietary solutions that support further development. =head2 LICENSE XML::Mini::Element module, part of the XML::Mini XML parser/generator package. Copyright (C) 2002-2008 Patrick Deegan All rights reserved XML::Mini is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XML::Mini is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XML::Mini. If not, see . Official XML::Mini site: http://minixml.psychogenic.com Contact page for author available on http://www.psychogenic.com/ =head1 SEE ALSO XML::Mini, XML::Mini::Document, XML::Mini::Element http://minixml.psychogenic.com =cut XML-Mini-1.38/lib/XML/Mini/Document.pm0000644000076400007670000010404210751723732017242 0ustar malcalypsecorbapackage XML::Mini::Document; use strict; $^W = 1; use FileHandle; use XML::Mini; use XML::Mini::Element; use XML::Mini::Element::Comment; use XML::Mini::Element::Header; use XML::Mini::Element::CData; use XML::Mini::Element::DocType; use XML::Mini::Element::Entity; use XML::Mini::Node; use vars qw ( $VERSION $TextBalancedAvailable ); use Text::Balanced; $TextBalancedAvailable = 1; $VERSION = '1.38'; if ($XML::Mini::IgnoreDeepRecursionWarnings) { XML::Mini->ignoreDeepRecursionWarning(); } sub new { my $class = shift; my $string = shift; my $self = {}; bless $self, ref $class || $class; $self->init(); if (defined $string) { $self->fromString($string); } return $self; } sub init { my $self = shift; delete $self->{'_xmlDoc'}; $self->{'_xmlDoc'} = XML::Mini::Element->new("PSYCHOGENIC_ROOT_ELEMENT"); } sub getRoot { my $self = shift; return $self->{'_xmlDoc'}; } sub setRoot { my $self = shift; my $root = shift; return XML::Mini->Error("XML::Mini::Document::setRoot(): Trying to set non-XML::Mini::Element as root") unless ($self->isElement($root)); $self->{'_xmlDoc'} = $root; } sub isElement { my $self = shift; my $element = shift || return undef; my $type = ref $element; return undef unless $type; return 0 unless ($type =~ /^XML::Mini::Element/); return 1; } sub isNode { my $self = shift; my $element = shift || return undef; my $type = ref $element; return undef unless $type; return 0 unless ($type =~ /^XML::Mini::Node/); return 1; } sub createElement { my $self = shift; my $name = shift; my $value = shift; # optional my $newElement = XML::Mini::Element->new($name); return XML::Mini->Error("Could not create new element named '$name'") unless ($newElement); if (defined $value) { $newElement->text($value); } return $newElement; } sub getElementByPath { my $self = shift; my $path = shift; my @elementNumbers = @_; my $element = $self->{'_xmlDoc'}->getElementByPath($path, @elementNumbers); if ($XML::Mini::Debug) { if ($element) { XML::Mini->Log("XML::Mini::Document::getElementByPath(): element at $path found."); } else { XML::Mini->Log("XML::Mini::Document::getElement(): element at $path NOT found."); } } return $element; } sub getElement { my $self = shift; my $name = shift; my $elementNumber = shift; # optionally get only the ith element my $element = $self->{'_xmlDoc'}->getElement($name, $elementNumber); if ($XML::Mini::Debug) { if ($element) { XML::Mini->Log("XML::Mini::Document::getElement(): element named $name found."); } else { XML::Mini->Log("XML::Mini::Document::getElement(): element named $name NOT found."); } } return $element; } sub fromString { my $self = shift; my $string = shift; if ($XML::Mini::CheckXMLBeforeParsing) { my $copy = $string; $copy =~ s/<\s*\?\s*xml.*?\?>//smg; $copy =~ s///smg; $copy =~s/]*>//smg; $copy =~ s/]*>//smg; $copy =~ s/]*>//smg; $copy =~ s/<\s*[^\s>]+[^>]*\/\s*>//smg; # get rid of tags # get rid of all pairs of tags... my %counts; while ($copy =~ m/<\s*([^\/\s>]+)[^>]*>/smg) { $counts{$1}->{'open'} = 0 unless (exists $counts{$1}->{'open'}); $counts{$1}->{'open'}++; } while ($copy =~ m/<\s*\/\s*([^\s>]+)(\s[^>]*)?>/smg) { $counts{$1}->{'close'} = 0 unless (exists $counts{$1}->{'close'}); $counts{$1}->{'close'}++; } # anything left my @unmatched; while (my ($tag, $res) = each %counts) { unless ($res->{'open'} && $res->{'close'} && $res->{'open'} == $res->{'close'} ) { push @unmatched, $tag; } } if (scalar @unmatched) { if ($XML::Mini::DieOnBadXML) { XML::Mini->Error("Found unmatched tags in your XML... " . join(',', @unmatched)); } else { XML::Mini->Log("Found unmatched tags in your XML... " . join(',', @unmatched)); } return 0; } # passed our basic check... } $self->fromSubString($self->{'_xmlDoc'}, $string); return $self->{'_xmlDoc'}->numChildren(); } sub fromFile { my $self = shift; my $filename = shift; my $fRef = \$filename; my $contents; if (ref($filename) && UNIVERSAL::isa($filename, 'IO::Handle')) { $contents = join("", $filename->getlines()); $filename->close(); } elsif (ref $fRef eq 'GLOB') { $contents = join('', $fRef->getlines()); $fRef->close(); } elsif (ref $fRef eq 'SCALAR') { return XML::Mini->Error("XML::Mini::Document::fromFile() Can't find file $filename") unless (-e $filename); return XML::Mini->Error("XML::Mini::Document::fromFile() Can't read file $filename") unless (-r $filename); my $infile = FileHandle->new(); $infile->open( "<$filename") || return XML::Mini->Error("XML::Mini::Document::fromFile() Could not open $filename for read: $!"); $contents = join("", $infile->getlines()); $infile->close(); } return $self->fromString($contents); } sub parse { my $self = shift; my $input = shift; my $inRef = \$input; my $type = ref($inRef); if ($type eq 'SCALAR' && $input =~ m|<[^>]+>|sm) { # we have some XML return $self->fromString($input); } else { # hope it's a file name or handle return $self->fromFile($input); } } sub fromHash { my $self = shift; my $href = shift || return XML::Mini->Error("XML::Mini::Document::fromHash - must pass a hash reference"); my $params = shift || {}; $self->init(); if ($params->{'attributes'}) { my %attribs; while (my ($attribName, $value) = each %{$params->{'attributes'}}) { my $vType = ref $value || ""; if ($vType) { if ($vType eq 'ARRAY') { foreach my $v (@{$value}) { $attribs{$attribName}->{$v}++; } } } else { $attribs{$attribName}->{$value}++; } } $params->{'attributes'} = \%attribs; } while (my ($keyname, $value) = each %{$href}) { my $sub = $self->_fromHash_getExtractSub(ref $value); $self->$sub($keyname, $value, $self->{'_xmlDoc'}, $params); } return $self->{'_xmlDoc'}->numChildren(); } sub _fromHash_getExtractSub { my $self = shift; my $valType = shift || 'STRING'; my $sub = "_fromHash_extract$valType"; return XML::Mini->Error("XML::Mini::Document::fromHash Don't know how to interpret '$valType' values") unless ($self->can($sub)); return $sub; } sub _fromHash_extractHASH { my $self = shift; my $name = shift; my $value = shift || return XML::Mini->Error("XML::Mini::Document::extractHASHref No value passed!"); my $parent = shift || return XML::Mini->Error("XML::Mini::Document::extractHASHref No parent element passed!"); my $params = shift || {}; return XML::Mini->Error("XML::Mini::Document::extractHASHref No element name passed!") unless (defined $name); my $thisElement = $parent->createChild($name); while (my ($key, $val) = each %{$value}) { my $sub = $self->_fromHash_getExtractSub(ref $val); $self->$sub($key, $val, $thisElement, $params); } return ; } sub _fromHash_extractARRAY { my $self = shift; my $name = shift; my $values = shift || return XML::Mini->Error("XML::Mini::Document::extractARRAYref No value passed!"); my $parent = shift || return XML::Mini->Error("XML::Mini::Document::extractARRAYref No parent element passed!"); my $params = shift || {}; return XML::Mini->Error("XML::Mini::Document::extractARRAYref No element name passed!") unless (defined $name); # every element in an array ref is a child element of the parent foreach my $val (@{$values}) { my $valRef = ref $val; if ($valRef) { # this is a complex element #my $childElement = $parent->createChild($name); # process sub elements my $sub = $self->_fromHash_getExtractSub($valRef); $self->$sub($name, $val, $parent, $params); } else { # simple string $self->_fromHash_extractSTRING($name, $val, $parent, $params); } } return; } sub _fromHash_extractSTRING { my $self = shift; my $name = shift; my $val = shift ; my $parent = shift || return XML::Mini->Error("XML::Mini::Document::extractSTRING No parent element passed!"); my $params = shift || {}; return XML::Mini->Error("XML::Mini::Document::extractSTRING No element name passed!") unless (defined $name); return XML::Mini->Error("XML::Mini::Document::extractSTRING No value passed!") unless (defined $val); my $pname = $parent->name(); if ($params->{'attributes'}->{$pname}->{$name} || $params->{'attributes'}->{'-all'}->{$name}) { $parent->attribute($name, $val); } elsif ($name eq '-content') { $parent->text($val); } else { $parent->createChild($name, $val); } return ; } sub toHash { my $self = shift; my $retVal = $self->{'_xmlDoc'}->toStructure(); my $type = ref $retVal; if ($type && $type eq 'HASH') { return $retVal; } my $retHash = { '-content' => $retVal, }; return $retHash; } sub toString { my $self = shift; my $depth = shift || 0; my $retString = $self->{'_xmlDoc'}->toString($depth); $retString =~ s/<\/PSYCHOGENIC_ROOT_ELEMENT>//smi; $retString =~ s/]*)?>\s*//smi; return $retString; } sub fromSubStringBT { my $self = shift; my $parentElement = shift; my $XMLString = shift; my $useIgnore = shift; if ($XML::Mini::Debug) { XML::Mini->Log("Called fromSubStringBT() with parent '" . $parentElement->name() . "'\n"); } my @res; if ($useIgnore) { my $ignore = [ '<\s*[^\s>]+[^>]*\/\s*>', # '<\?\s*[^\s>]+\s*[^>]*\?>', # '', # '\s*', # CDATA ']*)(\[.*?\])?\s*>', # DOCTYPE ']+>' ]; @res = Text::Balanced::extract_tagged($XMLString, undef, undef, undef, { 'ignore' => $ignore }); } else { @res = Text::Balanced::extract_tagged($XMLString); } if ($#res == 5) { # We've extracted a balanced .. my $extracted = $res[0]; # the entire .. my $remainder = $res[1]; # stuff after the ..HERE - 3 my $prefix = $res[3]; # the itself - 1 my $contents = $res[4]; # the '..' between .. - 2 my $suffix = $res[5]; # the #XML::Mini->Log("Grabbed prefix '$prefix'..."); my $newElement; if ($prefix =~ m|<\s*([^\s>]+)\s*([^>]*)>|) { my $name = $1; my $attribs = $2; $newElement = $parentElement->createChild($name); $self->_extractAttributesFromString($newElement, $attribs) if ($attribs); $self->fromSubStringBT($newElement, $contents) if ($contents =~ m|\S|); $self->fromSubStringBT($parentElement, $remainder) if ($remainder =~ m|\S|); } else { XML::Mini->Log("XML::Mini::Document::fromSubStringBT extracted balanced text from invalid tag '$prefix' - ignoring"); } } else { $XMLString =~ s/>\s*\n/>/gsm; if ($XMLString =~ m/^\s*<\s*([^\s>]+)([^>]*>).*<\s*\/\1\s*>/osm) { # starts with a normal ... but has some ?? in it my $startTag = $2; return $self->fromSubStringBT($parentElement, $XMLString, 'USEIGNORE') unless ($startTag =~ m|/\s*>$|); } # not a ... #it's either a if ($XMLString =~ m/^\s*(<\s*([^\s>]+)([^>]+)\/\s*>| # <\?\s*([^\s>]+)\s*([^>]*)\?>| # | # \s*| # CDATA ]*)(\[.*?\])?\s*>\s*| # DOCTYPE ]+)\s*(["'])([^\11]+)\11\s*>\s*| # ENTITY ([^<]+))(.*)/xogsmi) # plain text { my $firstPart = $1; my $unaryName = $2; my $unaryAttribs = $3; my $headerName = $4; my $headerAttribs= $5; my $comment = $6; my $cdata = $7; my $doctype = $8; my $doctypeCont = $9; my $entityName = $10; my $entityCont = $12; my $plainText = $13; my $remainder = $14; # There is some duplication here that should be merged with that in fromSubString() if ($unaryName) { my $newElement = $parentElement->createChild($unaryName); $self->_extractAttributesFromString($newElement, $unaryAttribs) if ($unaryAttribs); } elsif ($headerName) { my $newElement = XML::Mini::Element::Header->new($headerName); $self->_extractAttributesFromString($newElement, $headerAttribs) if ($headerAttribs); $parentElement->appendChild($newElement); } elsif (defined $comment) { $parentElement->comment($comment); } elsif (defined $cdata) { my $newElement = XML::Mini::Element::CData->new($cdata); $parentElement->appendChild($newElement); } elsif ($doctype || defined $doctypeCont) { my $newElement = XML::Mini::Element::DocType->new($doctype); $parentElement->appendChild($newElement); if ($doctypeCont) { $doctypeCont =~ s/^\s*\[//smg; $doctypeCont =~ s/\]\s*$//smg; $self->fromSubStringBT($newElement, $doctypeCont); } } elsif (defined $entityName) { my $newElement = XML::Mini::Element::Entity->new($entityName, $entityCont); $parentElement->appendChild($newElement); } elsif (defined $plainText && $plainText =~ m|\S|sm) { $parentElement->createNode($plainText); } else { XML::Mini->Log("NO MATCH???") if ($XML::Mini::Debug); } if (defined $remainder && $remainder =~ m|\S|sm) { $self->fromSubStringBT($parentElement, $remainder); } } else { # No match here either... XML::Mini->Log("No match in fromSubStringBT() for '$XMLString'") if ($XML::Mini::Debug); } # end if it matches one of our other tags or plain text } # end if Text::Balanced returned a match } # end fromSubStringBT() sub fromSubString { my $self = shift; my $parentElement = shift; my $XMLString = shift; if ($XML::Mini::Debug) { XML::Mini->Log("Called fromSubString() with parent '" . $parentElement->name() . "'\n"); } # The heart of the parsing is here, in our mega regex # The sections are for: # ... # # # # # # plain text #=~/<\s*([^\s>]+)([^>]+)?>(.*?)<\s*\/\\1\s*>\s*([^<]+)?(.*) if ($TextBalancedAvailable) { return $self->fromSubStringBT($parentElement, $XMLString); } while ($XMLString =~/\s*<\s*([^\s>]+)([^>]+)?>(.*?)<\s*\/\1\s*>\s*([^<]+)?(.*)| \s*\s*| \s*<\s*([^\s>]+)\s*([^>]*)\/\s*>\s*([^<>]+)?| \s*\s*| \s*]*)(\[.*?\])?\s*>\s*| \s*]+)\s*(["'])([^\14]+)\14\s*>\s*| \s*<\?\s*([^\s>]+)\s*([^>]*)\?>| ^([^<]+)(.*)/xogsmi) { # Check which string matched.' my $uname = $7; my $comment = $6; my $cdata = $10; my $doctypedef = $11; if ($12) { if ($doctypedef) { $doctypedef .= ' ' . $12; } else { $doctypedef = $12; } } my $entityname = $13; my $headername = $16; my $headerAttribs = $17; my $plaintext = $18; if (defined $uname) { my $ufinaltxt = $9; my $newElement = $parentElement->createChild($uname); $self->_extractAttributesFromString($newElement, $8); if (defined $ufinaltxt && $ufinaltxt =~ m|\S+|) { $parentElement->createNode($ufinaltxt); } } elsif (defined $headername) { my $newElement = XML::Mini::Element::Header->new($headername); $self->_extractAttributesFromString($newElement, $headerAttribs) if ($headerAttribs); $parentElement->appendChild($newElement); } elsif (defined $comment) { #my $newElement = XML::Mini::Element::Comment->new('!--'); #$newElement->createNode($comment); $parentElement->comment($comment); } elsif (defined $cdata) { my $newElement = XML::Mini::Element::CData->new($cdata); $parentElement->appendChild($newElement); } elsif (defined $doctypedef) { my $newElement = XML::Mini::Element::DocType->new($11); $parentElement->appendChild($newElement); $self->fromSubString($newElement, $doctypedef); } elsif (defined $entityname) { my $newElement = XML::Mini::Element::Entity->new($entityname, $15); $parentElement->appendChild($newElement); } elsif (defined $plaintext) { my $afterTxt = $19; if ($plaintext !~ /^\s+$/) { $parentElement->createNode($plaintext); } if (defined $afterTxt) { $self->fromSubString($parentElement, $afterTxt); } } elsif ($1) { my $nencl = $3; my $finaltxt = $4; my $otherTags = $5; my $newElement = $parentElement->createChild($1); $self->_extractAttributesFromString($newElement, $2); if ($nencl =~ /^\s*([^\s<][^<]*)/) { my $txt = $1; $newElement->createNode($txt); $nencl =~ s/^\s*[^<]+//; } $self->fromSubString($newElement, $nencl); if (defined $finaltxt) { $parentElement->createNode($finaltxt); } if (defined $otherTags) { $self->fromSubString($parentElement, $otherTags); } } } # end while matches } #* end method fromSubString */ sub toFile { my $self = shift; my $filename = shift || return XML::Mini->Error("XML::Mini::Document::toFile - must pass a filename to save to"); my $safe = shift; my $dir = $filename; $dir =~ s|(.+/)?[^/]+$|$1|; if ($dir) { return XML::Mini->Error("XML::Mini::Document::toFile - called with file '$filename' but cannot find director $dir") unless (-e $dir && -d $dir); return XML::Mini->Error("XML::Mini::Document::toFile - called with file '$filename' but no permission to write to dir $dir") unless (-w $dir); } my $contents = $self->toString(); return XML::Mini->Error("XML::Mini::Document::toFile - got nothing back from call to toString()") unless ($contents); my $outfile = FileHandle->new(); if ($safe) { if ($filename =~ m|/\.\./| || $filename =~ m|#;`\*|) { return XML::Mini->Error("XML::Mini::Document::toFile() Filename '$filename' invalid with SAFE flag on"); } if (-e $filename) { if ($safe =~ /NOOVERWRITE/i) { return XML::Mini->Error("XML::Mini::Document::toFile() file '$filename' exists and SAFE flag is '$safe'"); } if (-l $filename) { return XML::Mini->Error("XML::Mini::Document::toFile() file '$filename' is a " . "symbolic link and SAFE flag is on"); } } } $outfile->open( ">$filename") || return XML::Mini->Error("XML::Mini::Document::toFile() Could not open $filename for write: $!"); $outfile->print($contents); $outfile->close(); return length($contents); } sub getValue { my $self = shift; return $self->{'_xmlDoc'}->getValue(); } sub dump { my $self = shift; return Dumper($self); } #// _extractAttributesFromString #// private method for extracting and setting the attributs from a #// ' a="b" c = "d"' string sub _extractAttributesFromString { my $self = shift; my $element = shift; my $attrString = shift; return undef unless (defined $attrString); my $count = 0; while ($attrString =~ /([^\s]+)\s*=\s*(['"])([^\2]*?)\2/g) { my $attrname = $1; my $attrval = $3; if (defined $attrname) { $attrval = '' unless (defined $attrval && length($attrval)); $element->attribute($attrname, $attrval, ''); $count++; } } return $count; } 1; __END__ =head1 NAME XML::Mini::Document - Perl implementation of the XML::Mini Document API. =head1 SYNOPSIS use XML::Mini::Document; use Data::Dumper; ###### PARSING XML ####### # create a new object my $xmlDoc = XML::Mini::Document->new(); # init the doc from an XML string $xmlDoc->parse($XMLString); # You may use the toHash() method to automatically # convert the XML into a hash reference my $xmlHash = $xmlDoc->toHash(); print Dumper($xmlHash); # You can also manipulate the elements like directly, like this: # Fetch the ROOT element for the document # (an instance of XML::Mini::Element) my $xmlRoot = $xmlDoc->getRoot(); # play with the element and its children # ... my $topLevelChildren = $xmlRoot->getAllChildren(); foreach my $childElement (@{$topLevelChildren}) { # ... } ###### CREATING XML ####### # Create a new document from scratch my $newDoc = XML::Mini::Document->new(); # This can be done easily by using a hash: my $h = { 'spy' => { 'id' => '007', 'type' => 'SuperSpy', 'name' => 'James Bond', 'email' => 'mi5@london.uk', 'address' => 'Wherever he is needed most', }, }; $newDoc->fromHash($h); # Or new XML can also be created by manipulating #elements directly: my $newDocRoot = $newDoc->getRoot(); # create the header my $xmlHeader = $newDocRoot->header('xml'); # add the version $xmlHeader->attribute('version', '1.0'); my $person = $newDocRoot->createChild('person'); my $name = $person->createChild('name'); $name->createChild('first')->text('John'); $name->createChild('last')->text('Doe'); my $eyes = $person->createChild('eyes'); $eyes->attribute('color', 'blue'); $eyes->attribute('number', 2); # output the document print $newDoc->toString(); This example would output : John Doe =head1 DESCRIPTION The XML::Mini::Document class is the programmer's handle to XML::Mini functionality. A XML::Mini::Document instance is created in every program that uses XML::Mini. With the XML::Mini::Document object, you can access the root XML::Mini::Element, find/fetch/create elements and read in or output XML strings. =head2 new [XMLSTRING] Creates a new instance of XML::Mini::Document, optionally calling fromString with the passed XMLSTRING =head2 getRoot Returns a reference the this document's root element (an instance of XML::Mini::Element) =head2 setRoot NEWROOT setRoot NEWROOT Set the document root to the NEWROOT XML::Mini::Element object. =head2 isElement ELEMENT Returns a true value if ELEMENT is an instance of XML::Mini::Element, false otherwise. =head2 isNode NODE Returns a true value if NODE is an instance of XML::MiniNode, false otherwise. =head2 createElement NAME [VALUE] Creates a new XML::Mini::Element with name NAME. This element is an orphan (has no assigned parent) and will be lost unless it is appended (XML::Mini::Element::appendChild()) to an element at some point. If the optional VALUE (string or numeric) parameter is passed, the new element's text/numeric content will be set using VALUE. Returns a reference to the newly created element. =head2 getElement NAME [POSITON] Searches the document for an element with name NAME. Returns a reference to the first XML::Mini::Element with name NAME, if found, NULL otherwise. NOTE: The search is performed like this, returning the first element that matches: - Check the Root Element's immediate children (in order) for a match. - Ask each immediate child (in order) to XML::Mini::Element::getElement() (each child will then proceed similarly, checking all it's immediate children in order and then asking them to getElement()) If a numeric POSITION parameter is passed, getElement() will return only the POSITIONth element of name NAME (starting at 1). Thus, on document bob jane ralph $people->getElement('person') will return the element containing the text node 'bob', while $people->getElement('person', 3) will return the element containing the text 'ralph'. =head2 getElementByPath PATH [POSITIONARRAY] Attempts to return a reference to the (first) element at PATH where PATH is the path in the structure from the root element to the requested element. For example, in the document represented by: DA42 D99983FFF ss-839uent $accessid = $xmlDocument->getElementByPath('partRateRequest/vendor/accessid'); Will return what you expect (the accessid element with attributes user = "myusername" and password = "mypassword"). BUT be careful: my $accessid = $xmlDocument->getElementByPath('partRateRequest/partList/partNum'); will return the partNum element with the value "DA42". To access other partNum elements you must either use the POSITIONSARRAY or the getAllChildren() method on the partRateRequest element. POSITIONSARRAY functions like the POSITION parameter to getElement(), but instead of specifying the position of a single element, you must indicate the position of all elements in the path. Therefore, to get the third part number element, you would use my $thirdPart = $xmlDocument->getElementByPath('partRateRequest/partList/partNum', 1, 1, 3); The additional 1,1,3 parameters indicate that you wish to retrieve the 1st partRateRequest element in the document, the 1st partList child of partRateRequest and the 3rd partNum child of the partList element (in this instance, the partNum element that contains 'ss-839uent'). Returns the XML::Mini::Element reference if found, NULL otherwise. =head2 parse SOURCE Initialise the XML::Mini::Document (and its root XML::Mini::Element) using the XML from file SOURCE. SOURCE may be a string containing your XML document. In addition to parsing strings, possible SOURCEs are: # a file location string $miniXMLDoc->parse('/path/to/file.xml'); # an open file handle open(INFILE, '/path/to/file.xml'); $miniXMLDoc->parse(*INFILE); # an open FileHandle object my $fhObj = FileHandle->new(); $fhObj->open('/path/to/file.xml'); $miniXML->parse($fhObj); In all cases where SOURCE is a file or file handle, XML::Mini takes care of slurping the contents and closing the handle. =head2 fromHash HASHREF [OPTIONS] Parses a "hash representation" of your XML structure. For each key => value pair within the hash ref, XML::Mini will create an element of name 'key' : - with the text contents set to 'value' if 'value' is a string - for each element of 'value' if value is an ARRAY REFERENCE - with suitable children for each subkey => subvalue if 'value' is a HASH REFERENCE. For instance, if fromHash() is passed a simple hash ref like: my $h = { 'spy' => { 'id' => '007', 'type' => 'SuperSpy', 'name' => 'James Bond', 'email' => 'mi5@london.uk', 'address' => 'Wherever he is needed most', }, }; then : $xmlDoc->fromHash($h); print $xmlDoc->toString(); will output mi5@london.uk James Bond
Wherever he is needed most
SuperSpy 007
The optional OPTIONS parameter may be used to specify which keys to use as attributes (instead of creating subelements). For example, calling my $options = { 'attributes' => { 'spy' => 'id', 'email' => 'type', 'friend' => ['name', 'age'], } }; my $h = { 'spy' => { 'id' => '007', 'type' => 'SuperSpy', 'name' => 'James Bond', 'email' => { 'type' => 'private', '-content' => 'mi5@london.uk', }, 'address' => { 'type' => 'residential', '-content' => 'Wherever he is needed most', }, 'friend' => [ { 'name' => 'claudia', 'age' => 25, 'type' => 'close', }, { 'name' => 'monneypenny', 'age' => '40something', 'type' => 'tease', }, { 'name' => 'Q', 'age' => '10E4', 'type' => 'pain', } ], }, }; $xmlDoc->fromHash($h, $options); print $xmlDoc->toString(); will output something like: James Bond mi5@london.uk
residential Wherever he is needed most
SuperSpy close tease pain
As demonstrated above, you can use the optional href to specify tags for which attributes (instead of elements) should be created and you may nest hash and array refs to create complex structures. NOTE: Whenever a hash references is used you lose the sequence in which the elements are placed - only the array references (which create a list of identically named elements) can preserve their order. See ALSO: the documentation for the related toHash() method. Still TODO: Create some better docs for this! For the moment you can take a peek within the test suite of the source distribution. =head2 fromString XMLSTRING Initialise the XML::Mini::Document (and it's root XML::Mini::Element) using the XML string XMLSTRING. Returns the number of immediate children the root XML::Mini::Element now has. =head2 fromFile FILENAME Initialise the XML::Mini::Document (and it's root XML::Mini::Element) using the XML from file FILNAME. Returns the number of immediate children the root XML::Mini::Element now has. =head2 toString [DEPTH] Converts this XML::Mini::Document object to a string and returns it. The optional DEPTH may be passed to set the space offset for the first element. If the optional DEPTH is set to $XML::Mini::NoWhiteSpaces no \n or whitespaces will be inserted in the xml string (ie it will all be on a single line with no spaces between the tags. Returns a string of XML representing the document. =head2 toFile FILENAME [SAFE] Stringify and save the XML document to file FILENAME If SAFE flag is passed and is a true value, toFile will do some extra checking, refusing to open the file if the filename matches m|/\.\./| or m|#;`\*| or if FILENAME points to a softlink. In addition, if SAFE is 'NOOVERWRITE', toFile will fail if the FILENAME already exists. =head2 toHash Transform the XML structure internally represented within the object (created manually or parsed from a file or string) into a HASH reference and returns the href. For instance, if this XML is parse()d: mi5@london.uk James Bond
Wherever he is needed most
SuperSpy
I am not a man, I am a free number Number 6 prisoner@aol.com
6 Prison Island Road, Prison Island, Somewhere
The hash reference returned will look like this (as output by Data::Dumper): 'people' => { 'person' => [ { 'email' => 'mi5@london.uk', 'name' => 'James Bond', 'type' => 'SuperSpy', 'address' => 'Wherever he is needed most', 'id' => '007' }, { 'email' => { 'type' => 'private', '-content' => 'prisoner@aol.com' }, 'comment' => 'I am not a man, I am a free number', 'number' => '6', 'name' => 'Number 6', 'address' => '6 Prison Island Road, Prison Island, Somewhere', 'id' => '006' } ] } =head2 getValue Utility function, call the root XML::Mini::Element's getValue() =head2 dump Debugging aid, dump returns a nicely formatted dump of the current structure of the XML::Mini::Document object. =head1 CAVEATS It is impossible to parse "cross-nested" tags using regular expressions (i.e. sequences of the form ...). However, if you have the Text::Balanced module installed (it is installed by default with Perl 5.8), such sequences will be handled flawlessly. Even if you do not have the Text::Balanced module available, it is still possible to generate this type of XML - the problem only appears when parsing. =head1 AUTHOR Copyright (C) 2002-2008 Patrick Deegan, Psychogenic Inc. Programs that use this code are bound to the terms and conditions of the GNU GPL (see the LICENSE file). If you wish to include these modules in non-GPL code, you need prior written authorisation from the authors. This library is released under the terms of the GNU GPL version 3, making it available only for free programs ("free" here being used in the sense of the GPL, see http://www.gnu.org for more details). Anyone wishing to use this library within a proprietary or otherwise non-GPLed program MUST contact psychogenic.com to acquire a distinct license for their application. This approach encourages the use of free software while allowing for proprietary solutions that support further development. =head2 LICENSE XML::Mini::Document module, part of the XML::Mini XML parser/generator package. Copyright (C) 2002-2008 Patrick Deegan All rights reserved XML::Mini is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XML::Mini is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XML::Mini. If not, see . =head1 SEE ALSO XML::Mini, XML::Mini::Element http://minixml.psychogenic.com =cut XML-Mini-1.38/README0000644000076400007670000001270010751724261013701 0ustar malcalypsecorba XML::Mini Perl Module - Homepage and latest version: http://minixml.psychogenic.com INSTALLATION: 3 Methods are available: - CPAN # perl -MCPAN -e 'install XML::Mini' - Local perl Makefile.PL make make test su ; make install - Simple (no need for root priv) Since XML::Mini is a pure Perl implementation, you can simply tar zxvf XML-Mini-XXX.tar.gz mv lib/XML /path/to/destination and then, in your code, use: #!/usr/bin/perl use lib '/path/to/destination'; use XML::Mini::Document; # ... create and parse XML! NAME XML::Mini - Stand-alone, pure Perl implementation of the MiniXML XML generator and parser interface (http://minixml.psychogenic.com). SYNOPSIS use XML::Mini::Document; ############# Generate XML ############### # Create a new XML::Mini::Document my $newDoc = XML::Mini::Document->new(); # Creating XML can be done easily by using a hash ref: my $h = { 'spy' => { 'id' => '007', 'type' => 'SuperSpy', 'name' => 'James Bond', 'email' => 'mi5@london.uk', 'address' => 'Wherever he is needed most', }, }; $newDoc->fromHash($h); # output the XML print $newDoc->toString(); # Or new XML can also be created by manipulating # elements directly: my $newDocRoot = $newDoc->getRoot(); # create the header my $xmlHeader = $newDocRoot->header('xml'); # add the version $xmlHeader->attribute('version', '1.0'); my $person = $newDocRoot->createChild('person'); my $name = $person->createChild('name'); $name->createChild('first')->text('John'); $name->createChild('last')->text('Doe'); my $eyes = $person->createChild('eyes'); $eyes->attribute('color', 'blue'); $eyes->attribute('number', 2); # output the document print $newDoc->toString(); # ... ############# Parse XML ############### # Parse existing XML string my $xmlDoc = XML::Mini::Document->new(); $xmlDoc->parse($XMLString); # or $xmlDoc->parse('/path/to/file.xml'); # or $xmlDoc->parse(*INPUTFILEHANDLE); # Now we can fetch elements: my $part = $xmlDoc->getElementByPath('partsRateReply/part'); my $partId = $part->attribute('id'); my $price = $partList->getElement('price'); print "Part $partId costs: " . $price->getValue() . "\n"; DESCRIPTION XML::Mini is a set of Perl (and PHP) classes that allow you to access XML data and create valid XML output with a tree-based hierarchy of elements. It provides an easy, object-oriented interface for manipulating XML documents and their elements. It is currently being used to send requests and understand responses from remote servers in Perl or PHP applications. XML::Mini does not require any external libraries or modules. The XML::Mini.pm module includes a number of variable you may use to tweak XML::Mini's behavior. These include: $XML::Mini::AutoEscapeEntities - when greater than 0, the values set for nodes are automatically escaped, thus $element->text('4 is > 3') will set the contents of the appended node to '4 is > 3'. Default setting is 1. $XML::Mini::IgnoreWhitespaces - when greater than 0, extraneous whitespaces will be ignored (maily useful when parsing). Thus Hello There will be parsed as containing a text node with contents 'Hello There' instead of ' Hello There '. Default setting is 1. $XML::Mini::CaseSensitive - when greater than 0, element names are treated as case sensitive. Thus, $element->getElement('subelement') and $element->getElement('SubElement') will be equivalent. Defaults to 0. Class methods escapeEntites TOENCODE This method returns ToENCODE with HTML sensitive values (eg '<', '>', '"', etc) HTML encoded. Log MESSAGE Logs the message to STDERR Error MESSAGE Logs MESSAGE and exits the program, calling exit() AUTHOR Copyright (C) 2002-2008 Patrick Deegan, Psychogenic Inc. Programs that use this code are bound to the terms and conditions of the GNU GPL (see the LICENSE file). If you wish to include these modules in non-GPL code, you need prior written authorisation from the authors. This library is released under the terms of the GNU GPL version 3, making it available only for free programs ("free" here being used in the sense of the GPL, see http://www.gnu.org for more details). Anyone wishing to use this library within a proprietary or otherwise non-GPLed program MUST contact psychogenic.com to acquire a distinct license for their application. This approach encourages the use of free software while allowing for proprietary solutions that support further development. LICENSE XML::Mini XML parser/generator package. Copyright (C) 2002-2008 Patrick Deegan All rights reserved XML::Mini is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XML::Mini is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XML::Mini. If not, see . SEE ALSO http://minixml.psychogenic.com XML-Mini-1.38/LICENSE0000644000076400007670000010451210751724147014034 0ustar malcalypsecorba GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .