XML-Struct-0.26/0000775000175000017500000000000012535515543011553 5ustar vojvojXML-Struct-0.26/README0000644000175000017500000001057512535515543012441 0ustar vojvojNAME XML-Struct - Represent XML as data structure preserving element order SYNOPSIS use XML::Struct qw(readXML writeXML simpleXML removeXMLAttr); my $xml = readXML( "input.xml" ); # [ root => { xmlns => 'http://example.org/' }, [ '!', [ x => {}, [42] ] ] ] my $doc = writeXML( $xml ); # # !42 my $simple = simpleXML( $xml, root => 'record' ); # { record => { xmlns => 'http://example.org/', x => 42 } } my $xml2 = removeXMLAttr($xml); # [ root => [ '!', [ x => [42] ] ] ] DESCRIPTION XML::Struct implements a mapping between XML and Perl data structures. By default, the mapping preserves element order, so it also suits for "document-oriented" XML. In short, an XML element is represented as array reference with three parts: [ $name => \%attributes, \@children ] This data structure corresponds to the abstract data model of MicroXML , a simplified subset of XML. If your XML documents don't contain relevant attributes, you can also choose to map to this format: [ $name => \@children ] Both parsing (with XML::Struct::Reader or function readXML) and serializing (with XML::Struct::Writer or function writeXML) are fully based on XML::LibXML, so performance is better than XML::Simple and similar to XML::LibXML::Simple. MODULES XML::Struct::Reader Parse XML as stream into XML data structures. XML::Struct::Writer Write XML data structures to XML streams for serializing, SAX processing, or creating a DOM object. XML::Struct::Writer::Stream Simplified SAX handler for XML serialization. XML::Struct::Simple Transform XML data structure into simple form. FUNCTIONS The following functions are exported on request: readXML( $source [, %options ] ) Read an XML document with XML::Struct::Reader. The type of source (string, filename, URL, IO Handle...) is detected automatically. Options not known to XML::Struct::Reader are passed to XML::LibXML::Reader. writeXML( $xml [, %options ] ) Write an XML document/element with XML::Struct::Writer. simpleXML( $element [, %options ] ) Transform an XML document/element into simple key-value format as known from XML::Simple. See XML::Struct::Simple for configuration options. removeXMLAttr( $element ) Transform XML structure with attributes to XML structure without attributes. The function does not modify the passed element but creates a modified copy. EXAMPLE To give an example, with XML::Struct::Reader, this XML document: text text is transformed to this structure: [ "root", { }, [ [ "foo", { }, "text" ], [ "bar", { key => "value" }, [ "text", [ "doz", { }, [ ] ] ] ] ] This module also supports a simple key-value (aka "data-oriented") format, as used by XML::Simple. With option simple (or function simpleXML) the document given above would be transformed to this structure: { foo => "text", bar => { key => "value", doz => {} } } SEE ALSO This module was first created to be used in Catmandu::XML and turned out to also become a replacement for XML::Simple. See the former for more XML processing. XML::Twig is another popular and powerfull module for stream-based processing of XML documents. See XML::Smart, XML::Hash::LX, XML::Parser::Style::ETree, XML::Fast, and XML::Structured for different representations of XML data as data structures (feel free to implement converters from/to XML::Struct). XML::GenericJSON seems to be an outdated and incomplete attempt to capture more parts of XML Infoset in another data structure. See JSONx for a kind of reverse direction (JSON in XML). COPYRIGHT AND LICENSE This software is copyright (c) 2014 by Jakob Voß. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. XML-Struct-0.26/cpanfile0000644000175000017500000000006612535515543013257 0ustar vojvojrequires 'XML::LibXML', '2.0'; requires 'Moo', '1.0'; XML-Struct-0.26/META.yml0000644000175000017500000000142712535515543013026 0ustar vojvoj--- abstract: 'Represent XML as data structure preserving element order' author: - 'Jakob Voß' build_requires: {} configure_requires: Module::Build::Tiny: '0.039' dynamic_config: 0 generated_by: 'Dist::Milla version v1.0.15, Dist::Zilla version 5.020, CPAN::Meta::Converter version 2.142690' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: XML-Struct no_index: directory: - t - xt - inc - share - eg - examples requires: Moo: '1.0' XML::LibXML: '2.0' resources: bugtracker: https://github.com/nichtich/XML-Struct/issues homepage: https://github.com/nichtich/XML-Struct repository: https://github.com/nichtich/XML-Struct.git version: '0.26' x_contributors: - 'Jakob Voss ' XML-Struct-0.26/META.json0000644000175000017500000000266712535515543013205 0ustar vojvoj{ "abstract" : "Represent XML as data structure preserving element order", "author" : [ "Jakob Voß" ], "dynamic_config" : 0, "generated_by" : "Dist::Milla version v1.0.15, Dist::Zilla version 5.020, CPAN::Meta::Converter version 2.142690", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "XML-Struct", "no_index" : { "directory" : [ "t", "xt", "inc", "share", "eg", "examples" ] }, "prereqs" : { "configure" : { "requires" : { "Module::Build::Tiny" : "0.039" } }, "develop" : { "requires" : { "Dist::Milla" : "v1.0.15", "Test::Pod" : "1.41" } }, "runtime" : { "requires" : { "Moo" : "1.0", "XML::LibXML" : "2.0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/nichtich/XML-Struct/issues" }, "homepage" : "https://github.com/nichtich/XML-Struct", "repository" : { "type" : "git", "url" : "https://github.com/nichtich/XML-Struct.git", "web" : "https://github.com/nichtich/XML-Struct" } }, "version" : "0.26", "x_contributors" : [ "Jakob Voss " ] } XML-Struct-0.26/t/0000775000175000017500000000000012535515543012016 5ustar vojvojXML-Struct-0.26/t/reader-depth.t0000644000175000017500000000260212535515543014545 0ustar vojvojuse strict; use Test::More; use XML::Struct qw(readXML simpleXML); use Scalar::Util qw(reftype); sub sample { return readXML('t/nested.xml', @_) } my $simple = sample(simple => 1); is_deeply sample( simple => 1, depth => -1 ), $simple, 'simple, depth -1'; is_deeply sample( simple => 1, depth => undef ), $simple, 'simple, depth undef'; is_deeply sample( simple => 1, depth => 1, deep => 'simple'), $simple, 'simple, depth overridden by deep'; is_deeply sample( depth => 0, deep => 'simple'), $simple, 'depth 0, deep simple implies simple'; is_deeply sample( depth => 0, deep => 'simple', root => 1 ), sample( simple => 1, root => 1), 'depth 0, deep simple, root'; is_deeply sample( simple => 1, depth => 1 )->{foo}, [ [ foo => {}, [ [ 'bar' => {}, [] ] ] ] ], 'simple, depth 1'; is_deeply sample( simple => 1, depth => 2 )->{foo}->{bar}, [ [ bar => {}, [] ] ], 'simple, depth 2'; is_deeply sample( simple => 1, depth => 2, root => 1 )->{nested}->{foo}, [ [ foo => {}, [ [ bar => {}, [] ] ] ] ], 'simple, depth 2, root'; is_deeply sample( simple => 1, depth => 1, root => 1 )->{nested}, readXML('t/nested.xml'), 'simple 1, depth 1, root 1'; ok sample( depth => 0, deep => 'dom' )->isa('XML::LibXML::Element'), 'depth 0, deep dom'; like sample( depth => 0, deep => 'raw' ), qr{^.+$}sm, 'depth 0, deep raw'; done_testing; XML-Struct-0.26/t/release-pod-syntax.t0000644000175000017500000000045612535515543015732 0ustar vojvoj#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use Test::More; use Test::Pod 1.41; all_pod_files_ok(); XML-Struct-0.26/t/issue-10.t0000644000175000017500000000142412535515543013550 0ustar vojvojuse strict; use Test::More; use XML::Struct qw(readXML); my $xml = < BMC Womens Health 1 BMC Womens Health 2 XML my $simple = readXML($xml, simple => 1); is_deeply $simple, { journal => [ { type => 'nlm-ta', content => 'BMC Womens Health 1' }, { type => 'iso-abbrev', content => 'BMC Womens Health 2' } ] }, 'include content for simple XML'; $simple = readXML($xml, simple => 1, content => 'name' ); is_deeply $simple, { journal => [ { type => 'nlm-ta', name => 'BMC Womens Health 1' }, { type => 'iso-abbrev', name => 'BMC Womens Health 2' } ] }, 'include content for simple XML'; done_testing; XML-Struct-0.26/t/write-mixed.t0000644000175000017500000000274312535515543014445 0ustar vojvojuse strict; use Test::More; use XML::Struct::Writer; use Encode; my ($struct, $xml); sub write_xml { my $str = ""; my $args = ref $_[-1] ? pop : { xmldecl => 0 }; my $writer = XML::Struct::Writer->new( to => \$str, %$args ); $writer->write(@_); $str; } $struct = { foo => [0], bar => [], doz => ["Hello","World"], x => undef }; $xml = "HelloWorld0\n"; is write_xml($struct, "greet"), $xml, "simple format (with root)"; $struct = { foo => { bar => { doz => {} } } }; $xml = "\n"; is write_xml($struct, undef), $xml, "simple format (no root)"; is write_xml($struct, undef, { attributes => 0, xmldecl => 0 }), $xml, "simple format (no root, no attributes)"; $struct = [ micro => {}, [ { xml => 1 } ] ]; $xml = "1\n"; is write_xml($struct, undef), $xml, "mixed format (simple in micro)"; $struct = [ A => [ " ", { B => 1 }, " ", { B => [] } ] ]; $xml = " 1 \n"; is write_xml($struct, undef), $xml, "mixed format (simple in micro)"; $struct = { a => [ [ b => { a => 1 } ], [ c => { a => 1 }, ['d'] ] ] }; $xml = "d\n"; is write_xml($struct, undef), $xml, "mixed format (micro in simple)"; $xml = "d\n"; is write_xml($struct, undef, { attributes => 0, xmldecl => 0 }), $xml, "mixed format, no attributes"; done_testing; XML-Struct-0.26/t/struct.t0000644000175000017500000000115712535515543013531 0ustar vojvojuse strict; use Test::More; my $input = join "\n", '', '!42',''; use XML::Struct qw(readXML writeXML simpleXML removeXMLAttr); my $xml = readXML( \$input ); is_deeply $xml, [ root => { xmlns => 'http://example.org/' }, [ '!', [x => {}, [42]] ] ]; my $doc = writeXML( $xml ); is_deeply $doc, $input; my $simple = simpleXML( $xml, root => 'record' ); is_deeply $simple, { record => { xmlns => 'http://example.org/', x => 42 } }; my $xml2 = removeXMLAttr($xml); is_deeply $xml2, [ root => [ '!', [ x => [42] ] ] ]; done_testing; XML-Struct-0.26/t/flat.xml0000644000175000017500000000012712535515543013464 0ustar vojvoj 1 2 3 4 XML-Struct-0.26/t/nested.xml0000644000175000017500000000017312535515543014021 0ustar vojvoj X Y XML-Struct-0.26/t/writer.t0000644000175000017500000000501012535515543013511 0ustar vojvojuse strict; use Test::More; use XML::Struct::Writer; use Encode; my $writer = XML::Struct::Writer->new; my $struct = [ greet => { }, [ "Hello, ", [ emph => { color => "blue" } , [ "World" ] ], "!" ] ]; my $dom = $writer->writeDocument( $struct ); isa_ok $dom, 'XML::LibXML::Document'; my $xml = <<'XML'; Hello, World! XML is $dom->serialize, $xml, 'writeDocument via DOM'; my $str = ""; XML::Struct::Writer->new( to => \$str )->writeDocument($struct); is $str, $xml, 'writeDocument via SAX'; $struct = [ doc => { a => 1 }, [ "\x{2603}" ] ]; $xml = encode("UTF-8", < \x{2603} XML $dom = $writer->writeDocument($struct); is $dom->serialize, $xml, 'writeDocument with UTF-8 via DOM'; $str = ""; XML::Struct::Writer->new( to => \$str )->writeDocument($struct); is $str, $xml, 'writeDocument with UTF-8 via SAX'; $str = ""; XML::Struct::Writer->new( to => \$str, xmldecl => 0, pretty => 1 )->writeDocument($struct); $xml = encode("UTF-8", "\x{2603}\n"); is $str, $xml, 'omit xml declaration'; $struct = [ doc => [ [ name => [ "alice" ] ], [ name => [ "bob" ] ], ] ]; $xml = < alice bob XML $writer->attributes(0); $dom = $writer->writeDocument($struct); is $dom->serialize(1), $xml, "writeDocument indented, no attributes"; $str = ""; XML::Struct::Writer->new( to => \$str, pretty => 1, attributes => 0 )->writeDocument($struct); is $str, $xml, 'writeDocument pretty, no attributes via SAX'; { package MyHandler; use Moo; has buf => (is => 'rw', default => sub { [ ] }); sub start_document { push @{$_[0]->buf}, "start" } sub start_element { push @{$_[0]->buf}, $_[1] } sub end_element { push @{$_[0]->buf}, $_[1] } sub characters { push @{$_[0]->buf}, $_[1] } sub end_document { push @{$_[0]->buf}, "end"} sub result { $_[0]->buf } } $writer = XML::Struct::Writer->new( handler => MyHandler->new ); $xml = $writer->write( [ "foo", { x => 1 }, [ ["bar"], "text" ] ] ); is_deeply $xml, [ "start", { Name => "foo", Attributes => { x => 1 } }, { Name => "bar" }, { Name => "bar" }, { Data => "text" }, { Name => "foo" }, "end" ], 'custom handler'; $writer->xmldecl(0); $writer->to(\$str); $writer->write( [ "foo", { x => 1 } ] ); is $str, "\n", 'reset to/handler'; done_testing; XML-Struct-0.26/t/simple.t0000644000175000017500000000351012535515543013471 0ustar vojvojuse strict; use Test::More; use XML::Struct::Simple; my $micro = [ root => { xmlns => 'http://example.org/' }, [ '!', [ x => {}, [42] ] ] ]; sub convert { XML::Struct::Simple->new(@_)->transform($micro) } is_deeply convert( root => 'record' ), { record => { xmlns => 'http://example.org/', x => 42 } }, 'synopsis'; is_deeply convert(), { xmlns => 'http://example.org/', x => 42 }, 'root disabled by default'; is_deeply convert( root => 1 ), { root => { xmlns => 'http://example.org/', x => 42 } }, 'root enabled'; is_deeply convert( depth => 0 ), $micro, 'depth 0'; is_deeply explain convert( depth => 1 ), { xmlns => 'http://example.org/', x => [ [ x => {}, [42] ] ] }, 'depth 1'; is_deeply convert( depth => 1, root => 'r' ), { r => { xmlns => 'http://example.org/', x => [ [ x => {}, [42] ] ] } }, 'depth 1, root'; foreach ('remove','0') { is_deeply convert( root => 1, attributes => $_ ), { root => { x => 42 } }, 'remove attributes'; } is_deeply( XML::Struct::Simple->new->transform( [ root => [ ['text'] ] ] ), { text => {} }, 'empty tag'); # this was a bug until 0.25 is_deeply( XML::Struct::Simple->new->transform( [ root => [ ['text', {} ] ] ] ), { text => {} }, 'empty tag, no attributes'); is_deeply( XML::Struct::Simple->new( root => 1 )->transform( [ 'root' ] ), { root => {} }, 'empty '); is_deeply( XML::Struct::Simple->new->transform( [ root => ['text'] ] ), { root => 'text' }, 'special case text'); is_deeply( XML::Struct::Simple->new->transform( [ root => { x => 1 }, [] ] ), { x => 1 }, 'attributes only'); is_deeply( XML::Struct::Simple->new->transform( [ root => { x => 1 }, ['text'] ] ), { x => 1, content => 'text' }, 'mix attributes and text content'); done_testing; XML-Struct-0.26/t/reader.t0000644000175000017500000000703512535515543013450 0ustar vojvojuse strict; use Test::More; use XML::Struct qw(readXML); my ($data, $reader, $stream); $stream = XML::LibXML::Reader->new( string => " " ); $reader = XML::Struct::Reader->new; is_deeply $reader->read( $stream ), [ 'root', {}, [] ], 'skip whitespace'; $stream = XML::LibXML::Reader->new( string => " " ); $reader = XML::Struct::Reader->new( whitespace => 1 ); is_deeply $reader->read( $stream ), [ 'root' => { }, [' '] ], 'whitespace'; my $xml = <<'XML'; text text XML $data = readXML($xml); is_deeply $data, [ 'root', { 'b' => 'B', 'xmlns:x' => 'http://example.org/', 'x:a' => 'A' }, [ [ 'x:foo', { }, [ 'text' ] ], [ 'bar', { 'key' => 'value' }, [ "\n text\n ", [ 'doz', {}, [] ], "xx" ] ] ] ], 'readXML'; $data = readXML( $xml, ns => 'strip' ); is_deeply $data->[1], { a => 'A', b => 'B' }, 'strip attribute namespaces'; is_deeply $data->[2]->[0]->[0], 'foo', 'strip element namespaces'; eval { readXML( $xml, ns => 'disallow' ) }; like $@, qr{namespaces not allowed (at line \d+ )?at t/reader\.t}, 'disallow namespaces'; $data = readXML( '', ns => 'strip' ); is_deeply $data, ['x',{},[]], 'strip default namespace declaration'; eval { readXML( '', ns => 'disallow' ) }; like $@, qr{namespaces not allowed}, 'disallow namespaces attributes'; is_deeply readXML( 't/nested.xml', attributes => 0, ns => 'disallow' ), [ nested => [ [ items => [ [ a => ["X"] ] ] ], [ "foo" => [ [ "bar" ] ] ], [ items => [ [ "b" ], [ a => ["Y"] ], ] ] ] ], 'without attributes'; $xml = <<'XML'; ]> XML # FIXME: current reader does not respect DTD $xml = ''; is_deeply readXML( $xml, simple => 1 ), { attr => 42 }, 'mixed attributes'; is_deeply readXML( $xml, simple => 1, root => 1 ), { doc => { attr => 42 } }, 'mixed attributes'; is_deeply readXML( 't/flat.xml', simple => 1, root => 1, attributes => 0 ), { doc => { id => [1,2,4], xx => 3 } }, 'simple with root and without attributes'; my @nodes = readXML( 't/flat.xml', path => '/doc/id', simple => 1, root => 'xx' ); is_deeply \@nodes, [ { xx => 1 }, { xx => 2 }, { xx => 4 } ], 'list of nodes'; my $first = readXML( 't/flat.xml', path => '/doc/id', simple => 1, root => 'xx' ); is_deeply $first, { xx => 1 }, 'first of a list of nodes'; @nodes = (); $reader = XML::Struct::Reader->new( from => 't/flat.xml', simple => 1, root => 'n' ); push @nodes, $_ while $_ = $reader->readNext('/*/id'); is_deeply \@nodes, [ { n => 1 }, { n => 2 }, { n => 4 } ], 'read simple as loop'; # read from DOM my $dom = XML::LibXML->load_xml( string => "" ); is_deeply readXML($dom), [ root => { }, [ [ element => { }, [ ] ] ] ], 'read from XML::LibXML::Document'; is_deeply readXML($dom, simple => 1, root => 1), { root => { element => {} } }, 'empty tags in simple format'; is_deeply readXML($dom->documentElement), [ root => { }, [ [ element => { }, [ ] ] ] ], 'read from XML::LibXML::Element'; $dom = XML::LibXML->load_xml( string => "" ); is_deeply readXML( $dom, simple => 1, root => 1 ), { root => {} }, 'empty tag as root'; done_testing; XML-Struct-0.26/t/reader-path.t0000644000175000017500000000237712535515543014406 0ustar vojvojuse strict; use Test::More; use XML::Struct qw(readXML); my ($xml, $reader); sub init($) { my $path = shift; my $reader = XML::Struct::Reader->new( attributes => 0, path => $path, from => XML::LibXML::Reader->new( location => 't/nested.xml' ) ); is $reader->path, $path, "default path = '$path'"; return $reader; } for my $root (qw(* / /* /nested)) { $reader = init($root); $xml = $reader->readNext; is $xml->[0], 'nested', 'root'; } for my $root (qw(x /x //x)) { $reader = init($root); is $reader->readNext, undef, 'wrong namedroot'; } sub test_path(@) { my $reader; while (@_) { my $path = shift; my $result = shift; my $msg = shift; if (!$reader) { $reader = init($path); is_deeply $reader->readNext, $result, $msg; } else { my $next = $reader->readNext( $path ); is_deeply $next, $result, $msg; } } } test_path '/nested/items/*', [ a => ["X"] ], 'readNext (default path set)', undef, [ "b" ], 'readNext (reusing default path)', '//', [ a => ["Y"] ], 'readNext (relative)'; test_path '/nested/items/b', [ "b" ], 'readNext with name', '*', [ "a", ["Y"] ], '...'; done_testing; XML-Struct-0.26/Changes0000644000175000017500000000446212535515543013052 0ustar vojvojChangelog for XML-Struct 0.26 2015-06-09 09:53:04 CEST - fix builder support of Moo 1.0 - fix encoding of empty tag in simple format as {} 0.25 2015-05-22 15:05:07 CEST - allow resetting to/handler of writers - made most options only settable in constructors - refactored XML::Struct::Simple and improved tests - experimental reader option: deep (issue #16) 0.24 2015-05-18 15:34:22 CEST - simplified Writer, fix writing mixed XML - migrated build system to Milla - improved documentation 0.23 2014-06-27T22:00:46 - much more liberal XML writer - make all members mutable 0.22 2014-06-24T12:22:28 - fixed issue #10 - Merge branch 'master' into issue-10 - merged feature branches - refactored simpleXML to XML::Struct::Simple - unit test for issue #10 0.21 2014-06-22T21:13:53 - fix pretty serialization w/o xmldecl - add and test xmldecl 0.20 2014-06-22T10:40:04 - include XML serializer (issue #6) 0.19 2014-06-19T07:20:35 - avoid quote_sub failure 0.18 2014-06-12T13:47:30 - removed debug statement 0.17 2014-06-12T12:08:50 - readXML from STDIN by default (close #9) - support reading from XML::LibXML::Document/Element 0.16 2014-02-20T09:25:51 - fixed empty element bug in simpleXML 0.15 2013-09-23T10:22:03 - align empty XML elements with MicroXML data model - new option: ns=>'disallow' - fix namespace stripping attributes - Document parallels to MicroXML 0.14 2013-09-19T06:56:00 - fully enable option depth 0.13 2013-09-17T12:17:43 - new option 'depth' for simpleXML - support namespace stripping 0.12 2013-09-17T09:35:19 - Support '//' in pathes 0.11 2013-09-12T08:17:16 - new function removeXMLAttr - renamed 'hashify' to 'simple' 0.10 2013-09-11T12:04:45 - renamed 'hashify' to 'simple' 0.06 2013-09-11T10:31:11 - bumped version - added method readDocument - fixed hashification with root - improved writer with options 'encoding' and 'version' 0.05 2013-09-10T12:09:48 - removed test artifact 0.04 2013-09-10T11:50:06 - improved path matching - support hashify root aka KeepRoot 0.03 2013-09-09T08:32:40 - added function hashifyXML - extended writer - fix reader test - implemented writer - don't test on Perl 5.8 with travis - first draft of writer 0.02 2013-09-08T09:19:25 - renamed to XML::Struct - added writer 0.01 2013-09-06T22:50:43 - initial draft XML-Struct-0.26/LICENSE0000644000175000017500000004365212535515543012570 0ustar vojvojThis software is copyright (c) 2014 by Jakob Voß.. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2014 by Jakob Voß.. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. END OF TERMS AND CONDITIONS Appendix: 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 humanity, 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 convey 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) 19yy 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 1, 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision 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, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2014 by Jakob Voß.. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End XML-Struct-0.26/Build.PL0000644000175000017500000000025512535515543013047 0ustar vojvoj# This Build.PL for XML-Struct was generated by Dist::Zilla::Plugin::ModuleBuildTiny 0.010. use strict; use warnings; use 5.006; use Module::Build::Tiny 0.039; Build_PL(); XML-Struct-0.26/lib/0000775000175000017500000000000012535515543012321 5ustar vojvojXML-Struct-0.26/lib/XML/0000775000175000017500000000000012535515543012761 5ustar vojvojXML-Struct-0.26/lib/XML/Struct.pm0000644000175000017500000001376212535515543014612 0ustar vojvojpackage XML::Struct; use strict; use XML::LibXML::Reader; use XML::Struct::Reader; use XML::Struct::Writer; use XML::Struct::Simple; our $VERSION = '0.26'; our @ISA = qw(Exporter); our @EXPORT_OK = qw(readXML writeXML simpleXML removeXMLAttr textValues); sub readXML { # ( [$from], %options ) my (%options) = @_ % 2 ? (from => @_) : @_; my %reader_options = ( map { $_ => delete $options{$_} } grep { exists $options{$_} } qw(attributes whitespace path stream simple micro root ns depth content deep) ); if (%options) { if (exists $options{from} and keys %options == 1) { $reader_options{from} = $options{from}; } else { $reader_options{from} = \%options; } } XML::Struct::Reader->new( %reader_options )->readDocument; } sub writeXML { my ($xml, %options) = @_; XML::Struct::Writer->new(%options)->write($xml); } sub simpleXML { my ($element, %options) = @_; XML::Struct::Simple->new(%options)->transform($element); } *removeXMLAttr = *XML::Struct::Simple::removeXMLAttr; # TODO: document (better name?) sub textValues { my ($element, $options) = @_; # TODO: %options (e.g. join => " ") my $children = $element->[2]; return "" if !$children; return join "", grep { $_ ne "" } map { ref $_ ? textValues($_, $options) : $_ } @$children; } 1; __END__ =encoding utf8 =head1 NAME XML-Struct - Represent XML as data structure preserving element order =begin markdown # Status [![Build Status](https://travis-ci.org/nichtich/XML-Struct.png)](https://travis-ci.org/nichtich/XML-Struct) [![Coverage Status](https://coveralls.io/repos/nichtich/XML-Struct/badge.png)](https://coveralls.io/r/nichtich/XML-Struct) [![Kwalitee Score](http://cpants.cpanauthors.org/dist/XML-Struct.png)](http://cpants.cpanauthors.org/dist/XML-Struct) =end markdown =head1 SYNOPSIS use XML::Struct qw(readXML writeXML simpleXML removeXMLAttr); my $xml = readXML( "input.xml" ); # [ root => { xmlns => 'http://example.org/' }, [ '!', [ x => {}, [42] ] ] ] my $doc = writeXML( $xml ); # # !42 my $simple = simpleXML( $xml, root => 'record' ); # { record => { xmlns => 'http://example.org/', x => 42 } } my $xml2 = removeXMLAttr($xml); # [ root => [ '!', [ x => [42] ] ] ] =head1 DESCRIPTION L implements a mapping between XML and Perl data structures. By default, the mapping preserves element order, so it also suits for "document-oriented" XML. In short, an XML element is represented as array reference with three parts: [ $name => \%attributes, \@children ] This data structure corresponds to the abstract data model of L, a simplified subset of XML. If your XML documents don't contain relevant attributes, you can also choose to map to this format: [ $name => \@children ] Both parsing (with L or function C) and serializing (with L or function C) are fully based on L, so performance is better than L and similar to L. =head1 MODULES =over =item L Parse XML as stream into XML data structures. =item L Write XML data structures to XML streams for serializing, SAX processing, or creating a DOM object. =item L Simplified SAX handler for XML serialization. =item L Transform XML data structure into simple form. =back =head1 FUNCTIONS The following functions are exported on request: =head2 readXML( $source [, %options ] ) Read an XML document with L. The type of source (string, filename, URL, IO Handle...) is detected automatically. Options not known to XML::Struct::Reader are passed to L. =head2 writeXML( $xml [, %options ] ) Write an XML document/element with L. =head2 simpleXML( $element [, %options ] ) Transform an XML document/element into simple key-value format as known from L. See L for configuration options. =head2 removeXMLAttr( $element ) Transform XML structure with attributes to XML structure without attributes. The function does not modify the passed element but creates a modified copy. =head1 EXAMPLE To give an example, with L, this XML document: text text is transformed to this structure: [ "root", { }, [ [ "foo", { }, "text" ], [ "bar", { key => "value" }, [ "text", [ "doz", { }, [ ] ] ] ] ] This module also supports a simple key-value (aka "data-oriented") format, as used by L. With option C (or function C) the document given above would be transformed to this structure: { foo => "text", bar => { key => "value", doz => {} } } =head1 SEE ALSO This module was first created to be used in L and turned out to also become a replacement for L. See the former for more XML processing. L is another popular and powerfull module for stream-based processing of XML documents. See L, L, L, L, and L for different representations of XML data as data structures (feel free to implement converters from/to XML::Struct). L seems to be an outdated and incomplete attempt to capture more parts of XML Infoset in another data structure. See JSONx for a kind of reverse direction (JSON in XML). =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2014 by Jakob Voß. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut XML-Struct-0.26/lib/XML/Struct/0000775000175000017500000000000012535515543014245 5ustar vojvojXML-Struct-0.26/lib/XML/Struct/Simple.pm0000644000175000017500000001225112535515543016033 0ustar vojvojpackage XML::Struct::Simple; use strict; use Moo; use List::Util qw(first); use Scalar::Util qw(reftype blessed); our $VERSION = '0.26'; has root => ( is => 'rw', default => sub { 0 }, ); has attributes => ( is => 'rw', default => sub { 1 }, coerce => sub { !defined $_[0] or ($_[0] and $_[0] ne 'remove') }, ); has content => ( is => 'rw', default => sub { 'content' }, ); has depth => ( is => 'rw', coerce => sub { (defined $_[0] and $_[0] >= 0) ? $_[0] : undef }, ); sub transform { my ($self, $element) = @_; my $simple = $self->transform_content($element,0); # enforce root for special case text if ($self->root or !ref $simple) { my $root = $self->root !~ /^[+-]?[0-9]+$/ ? $self->root : $element->[0]; return { $root => $simple }; } else { return $simple; } } # returns a (possibly empty) hash or a scalar sub transform_content { my ($self, $element, $depth) = @_; $depth = 0 if !defined $depth; if (defined $self->depth and $depth >= $self->depth) { return $element; } elsif ( @$element == 1 ) { # empty tag return { }; } my $attributes = {}; my $children; if ( reftype $element->[1] eq 'HASH' ) { # [ $tag, \%attributes, \@children ] $attributes = $element->[1] if $self->attributes; $children = $element->[2]; } else { # [ $tag, \@children ] $children = $element->[1]; } # no element children unless ( first { ref $_ } @$children ) { my $content = join "", @$children; if ($content eq '') { return { %$attributes }; } elsif (!%$attributes) { return $content; } else { return { %$attributes, $self->content => $content }; } } my $simple = { map {$_ => [$attributes->{$_}] } keys %$attributes }; foreach my $child ( @$children ) { next unless ref $child; # skip mixed content text my $name = $child->[0]; my $content = $self->transform_content($child, $depth+1); if ( $simple->{$name} ) { push @{$simple->{$name}}, $content; } else { $simple->{$name} = [$content]; } } foreach my $name (keys %$simple) { next if @{$simple->{$name}} != 1; my $c = $simple->{$name}->[0]; if (!ref $c or (!blessed $c and reftype $c eq 'HASH')) { $simple->{$name} = $c; } } return $simple; } sub removeXMLAttr { my $node = shift; ref $node ? ( $node->[2] ? [ $node->[0], [ map { removeXMLAttr($_) } @{$node->[2]} ] ] : [ $node->[0] ] ) # empty element : $node; # text node } 1; __END__ =encoding UTF-8 =head1 NAME XML::Struct::Simple - Transform MicroXML data structures into simple (unordered) form =head1 SYNOPSIS my $micro = [ root => { xmlns => 'http://example.org/' }, [ '!', [ x => {}, [42] ] ] ]; my $converter = XML::Struct::Simple->new( root => 'record' ); my $simple = $converter->transform( $micro ); # { record => { xmlns => 'http://example.org/', x => 42 } } =head1 DESCRIPTION This module implements a transformation from structured XML (MicroXML) to simple key-value format (SimpleXML) as known from L: Attributes and child elements are treated as hash keys with their content as value. Text elements without attributes are converted to text and empty elements without attributes are converted to empty hashes. L can export the function C for easy use. Function C and L apply transformation to SimpleXML with option C. =head1 METHODS =head2 transform( $element ) Transform XML given as array reference (MicroXML) to XML as hash reference (SimpleXML) as configured. =head2 transform_content( $element [, $depth ] ) Transform child nodes and attributes of an XML element given as array reference at a given depth (C<0> by default). Returns a hash reference, a scalar, or the element unmodified. =head1 CONFIGURATION =over =item root Keep the root element instead of removing. This corresponds to option C in L. In addition a non-numeric value can be used to override the name of the root element. Disabled by default. =item attributes Include XML attributes. Enabled by default. The special value C is equivalent to false. Corresponds to option C in L. =item content Name of a field to put text content in. Set to "C by default. Corresponds to option C in L. =item depth Only transform up to a given depth. Set to a negative value by default for unlimited depth. Elements below depth are not cloned but copied by reference. Depth 0 will return the element unmodified. =back Option C, C, and other fetures of L not supported. Options C and C supported in L are not supported yet. =head2 FUNCTIONS =head2 removeXMLAttr( $element ) Recursively remove XML attributes from XML given as array reference (MicroXML). This function is deprecated. =cut XML-Struct-0.26/lib/XML/Struct/Reader.pm0000644000175000017500000003057712535515543016017 0ustar vojvojpackage XML::Struct::Reader; use strict; use Moo; use Carp qw(croak); our @CARP_NOT = qw(XML::Struct); use Scalar::Util qw(blessed); use XML::Struct; our $VERSION = '0.26'; has whitespace => (is => 'ro', default => sub { 0 }); has attributes => (is => 'ro', default => sub { 1 }); has path => (is => 'ro', default => sub { '*' }, isa => \&_checkPath); has stream => (is => 'rw', lazy => 1, builder => 1, isa => sub { die 'stream must be an XML::LibXML::Reader' unless blessed $_[0] && $_[0]->isa('XML::LibXML::Reader'); } ); has from => (is => 'ro', trigger => 1); has ns => (is => 'ro', default => sub { 'keep' }, trigger => 1); has depth => (is => 'ro', coerce => sub { (defined $_[0] and $_[0] =~ /^\+?\d+/) ? $_[0] : undef }); has deep => (is => 'ro', default => sub { '' } ); has simple => (is => 'ro', default => sub { 0 }); has root => (is => 'ro', default => sub { 0 }); has content => (is => 'ro', default => sub { 'content' }); use XML::LibXML::Reader qw( XML_READER_TYPE_ELEMENT XML_READER_TYPE_TEXT XML_READER_TYPE_CDATA XML_READER_TYPE_SIGNIFICANT_WHITESPACE XML_READER_TYPE_END_ELEMENT ); sub BUILD { my ($self) = @_; # make sure that option 'deep' and 'depth' are only set if it makes sense if ($self->deep eq 'simple') { if ($self->simple or (defined $self->depth and $self->depth == 0)) { # (deep = simple, simple = 1) or (deep = simple, depth = 0) $self->{simple} = 1; delete $self->{depth}; $self->{deep} = ''; } } elsif ($self->deep eq 'struct') { $self->{deep} = ''; } elsif ($self->deep eq '') { $self->{deep} = $self->simple ? '' : 'simple'; } elsif ($self->deep !~ /^(dom|raw)$/) { croak "option deep must be simple, struct, dom, or raw!"; } if (($self->depth || 0) and $self->root and $self->simple) { $self->{depth} = $self->{depth}-1; } } sub _build_stream { XML::LibXML::Reader->new( { IO => \*STDIN } ) } sub _trigger_from { my ($self, $from) = @_; unless (blessed $from and $from->isa('XML::LibXML::Reader')) { my %options; if (ref $from and ref $from eq 'HASH') { %options = %$from; $from = delete $options{from} if exists $options{from}; } if (!defined $from or $from eq '-') { $options{IO} = \*STDIN } elsif( !ref $from and $from =~ /^isa('XML::LibXML::Document') ) { $options{DOM} = $from; } elsif( blessed $from and $from->isa('XML::LibXML::Element') ) { my $doc = XML::LibXML->createDocument; $doc->setDocumentElement($from); $options{DOM} = $doc; } elsif( blessed $from ) { $options{IO} = $from; } elsif( !ref $from ) { $options{location} = $from; # filename or URL } elsif( ! grep { $_ =~ /^(IO|string|location|FD|DOM)$/} keys %options ) { croak "invalid option 'from': $from"; } $from = XML::LibXML::Reader->new( %options ) or die "failed to create XML::LibXML::Reader with " . join(', ',map { "$_=".$options{$_} } keys %options )."\n"; } $self->stream($from); } sub _trigger_ns { my ($self, $ns) = @_; if (!defined $ns or $ns eq '') { $self->{ns} = 'keep'; } elsif ($ns !~ /^(keep|strip|disallow)?$/) { croak "invalid option 'ns': $ns"; } } sub _checkPath { my $path = shift; die "invalid path: $path" if $path =~ qr{\.\.|.//|^\.}; die "relative path not supported: $path" if $path =~ qr{^[^/]+/}; return $path; } sub _nameMatch { return ($_[0] eq '*' or $_[0] eq $_[1]); } # read to the next element # TODO: use XML::LibXML->nextPatternMatch sub _nextPatternMatch { my ($self, $stream, $path) = @_; $path =~ s{^//}{}; $path .= '*' if $path =~ qr{^$|/$}; my @parts = split '/', $path; my $relative = $parts[0] ne ''; while(1) { return if !$stream->read; # end or error next if $stream->nodeType != XML_READER_TYPE_ELEMENT; # printf " %d=%d %s:%s==%s\n", $stream->depth, scalar @parts, $stream->nodePath, $stream->name, join('/', @parts); my $name = $self->_name($stream); if ($relative) { if (_nameMatch($parts[0], $name)) { last; } } else { if (!_nameMatch($parts[$stream->depth+1], $name)) { $stream->nextSibling(); } elsif ($stream->depth == scalar @parts - 2) { last; } } } return 1; } sub readNext { my $self = shift; my $stream = blessed $_[0] ? shift() : $self->stream; my $path = defined $_[0] ? _checkPath($_[0]) : $self->path; return unless $self->_nextPatternMatch($stream, $path); my $xml = $self->readElement($stream); return $self->simple ? XML::Struct::Simple->new( root => $self->root, attributes => $self->attributes, depth => $self->depth, content => $self->content, )->transform($xml) : $xml; } *read = \&readNext; sub readDocument { my $self = shift; my @document; while(my $element = $self->read(@_)) { return $element unless wantarray; push @document, $element; } return @document; } sub _name { my ($self, $stream) = @_; if ($self->ns eq 'strip') { return $stream->localName; } elsif( $self->ns eq 'disallow' ) { if ( $stream->name =~ /^xmlns(:.*)?$/) { croak "namespaces not allowed at line ".$stream->lineNumber; } } return $stream->name; } sub readElement { my $self = shift; my $stream = @_ ? shift : $self->stream; my @element = ($self->_name($stream)); # TODO: dom or raw if (defined $self->depth and $stream->depth >= $self->depth) { if ($self->deep eq 'dom') { my $dom = $stream->copyCurrentNode(1); $stream->next; return $dom; } elsif ($self->deep eq 'raw') { my $xml = $stream->readOuterXml(); $stream->next; return $xml; } #copyCurrentNode #if (defined $self->depth and $self->depth == $stream->depth ) { #print $stream->depth." ".$self->deep."!".$element[0]."\n"; #} } if ($self->attributes) { my $attr = $self->readAttributes($stream); my $children = $stream->isEmptyElement ? [ ] : $self->readContent($stream); push @element, $attr, $children; } elsif( !$stream->isEmptyElement ) { push @element, $self->readContent($stream); } return \@element; } sub readAttributes { my $self = shift; my $stream = @_ ? shift : $self->stream; return { } if $stream->moveToFirstAttribute != 1; my $attr = { }; do { if ($self->ns ne 'strip' or $stream->name !~ /^xmlns(:.*)?$/) { $attr->{ $self->_name($stream) } = $stream->value; } } while ($stream->moveToNextAttribute); $stream->moveToElement; return $attr; } sub readContent { my $self = shift; my $stream = @_ ? shift : $self->stream; my @children; while(1) { $stream->read; my $type = $stream->nodeType; last if !$type or $type == XML_READER_TYPE_END_ELEMENT; if ($type == XML_READER_TYPE_ELEMENT) { push @children, $self->readElement($stream); } elsif ($type == XML_READER_TYPE_TEXT or $type == XML_READER_TYPE_CDATA ) { push @children, $stream->value; } elsif ($type == XML_READER_TYPE_SIGNIFICANT_WHITESPACE && $self->whitespace) { push @children, $stream->value; } } return \@children; } 1; __END__ =encoding UTF-8 =head1 NAME XML::Struct::Reader - Read XML streams into XML data structures =head1 SYNOPSIS my $reader = XML::Struct::Reader->new( from => "file.xml" ); my $data = $reader->read; =head1 DESCRIPTION This module reads an XML stream (via L) into L/MicroXML data structures. =head1 METHODS =head2 read = readNext ( [ $stream ] [, $path ] ) Read the next XML element from a stream. If no path option is specified, the reader's path option is used ("C<*>" by default, first matching the root, then every other element). =head2 readDocument( [ $stream ] [, $path ] ) Read an entire XML document. In contrast to C/C, this method always reads the entire stream. The return value is the first element (that is the root element by default) in scalar context and a list of elements in array context. Multiple elements can be returned for instance when a path was specified to select document fragments. =head2 readElement( [ $stream ] ) Read an XML element from a stream and return it as array reference with element name, attributes, and child elements. In contrast to method C, this method expects the stream to be at an element node (C<< $stream->nodeType == 1 >>) or bad things might happed. =head2 readAttributes( [ $stream ] ) Read all XML attributes from a stream and return a (possibly empty) hash reference. =head2 readContent( [ $stream ] ) Read all child elements of an XML element and return the result as (possibly empty) array reference. Significant whitespace is only included if option C is enabled. =head1 CONFIGURATION =over =item from A source to read from. Possible values include a string or string reference with XML data, a filename, an URL, a file handle, instances of L or L, and a hash reference with options passed to L. =item stream A L to read from. If no stream has been defined, one must pass a stream parameter to the C methods. Setting a source with option C automatically sets a stream. =item attributes Include attributes (enabled by default). If disabled, the representation of an XML element will be [ $name => \@children ] instead of [ $name => \%attributes, \@children ] =item path Optional path expression to be used as default value when calling C. Pathes must either be absolute (starting with "C") or consist of a single element name. The special name "C<*>" matches all element names. A path is a very reduced form of an XPath expressions (no axes, no "C<..>", no node tests, C only at the start...). Namespaces are not supported yet. =item whitespace Include ignorable whitespace as text elements (disabled by default) =item ns Define how XML namespaces should be processed. By default (value 'C'), this document: is transformed to this structure, keeping namespace prefixes and declarations as unprocessed element names and attributes: [ 'doc', {}, [ [ 'x:foo', { 'bar' => 'doz', 'xmlns:x' => 'http://example.org/' } ] ] Setting this option to 'C' will remove all namespace prefixes and namespace declaration attributes, so the result would be: [ 'doc', {}, [ [ 'foo', { 'bar' => 'doz' } ] ] Setting this option to 'C' results in an error when namespace prefixes or declarations are read. Expanding namespace URIs ('C) is not supported yet. =item simple Convert XML to simple key-value structure (SimpleXML) with L. =item depth Only transform to a given depth, starting at C<0> for the root node. Negative values, non-numeric values or C are ignored (unlimited depth as default). XML elements below the depth are converted to SimpleXML by default or to MicroXML if option C is enabled. This can be configured with option C. This option is useful for instance to access document-oriented XML embedded in data oriented XML. =item deep How to transform elements below given C. This option is experimental. =item root Include root element when converting to SimpleXML. Disabled by default. =item content Name of text content when converting to SimpleXML. =back =cut XML-Struct-0.26/lib/XML/Struct/Writer/0000775000175000017500000000000012535515543015521 5ustar vojvojXML-Struct-0.26/lib/XML/Struct/Writer/Stream.pm0000644000175000017500000000670112535515543017314 0ustar vojvojpackage XML::Struct::Writer::Stream; use strict; use Moo; our $VERSION = '0.26'; has fh => (is => 'rw', default => sub { *STDOUT }); has pretty => (is => 'rw'); our %ESCAPE = ( '&' => '&', '<' => '<', '>' => '>', '"' => '"', ); use constant { DOCUMENT_STARTED => 0, TAG_STARTED => 1, CHAR_CONTENT => 2, CHILD_ELEMENT => 3, }; sub xml_decl { my ($self, $data) = @_; my $xml = "{Version}\""; $xml .= " encoding=\"$data->{Encoding}\"" if $data->{Encoding}; $xml .= " standalone=\"$data->{Standalone}\"" if $data->{Standalone}; $xml .= "?>\n"; print {$self->fh} $xml; } sub start_document { my ($self) = @_; $self->{_stack} = []; $self->{_status} = DOCUMENT_STARTED; } sub start_element { my ($self, $data) = @_; my $tag = $data->{Name}; my $attr = $data->{Attributes}; my $xml = "<$tag"; if ($self->{_status} == TAG_STARTED) { print {$self->fh} '>'; if ($self->pretty) { print {$self->fh} "\n".(' ' x (scalar @{$self->{_stack}})); } } elsif ($self->{_status} == CHILD_ELEMENT) { if ($self->pretty) { print {$self->fh} "\n".(' ' x (scalar @{$self->{_stack}})); } } elsif ($self->{_status} == CHAR_CONTENT) { print {$self->fh} $self->{_chars}; } # else: DOCUMENT_STARTED push @{$self->{_stack}}, $tag; if ($attr && %$attr) { foreach my $key (sort keys %$attr) { my $value = $attr->{$key}; $value =~ s/([&<>"'])/$ESCAPE{$1}/geo; $xml .= " $key=\"$value\""; } } $self->{_status} = TAG_STARTED; print {$self->fh} $xml; } sub end_element { my ($self) = @_; my $tag = pop @{$self->{_stack}} or return; if ($self->{_status} == TAG_STARTED) { print {$self->fh} '/>'; } elsif ($self->{_status} == CHAR_CONTENT) { print {$self->fh} $self->{_chars} . ""; $self->{_chars} = ""; } else { # CHILD_ELEMENT if ($self->pretty) { print {$self->fh} "\n".(' ' x (scalar @{$self->{_stack}})); } print {$self->fh} ""; } $self->{_status} = CHILD_ELEMENT; } sub characters { my ($self, $data) = @_; my $xml = $data->{Data}; $xml =~ s/([&<>])/$ESCAPE{$1}/geo; if ($self->{_status} == TAG_STARTED) { print {$self->fh} '>'; $self->{_status} = CHAR_CONTENT; $self->{_chars} = $xml; } elsif ($self->{_status} == CHILD_ELEMENT) { print {$self->fh} $xml; } else { $self->{_chars} .= $xml; } } sub end_document { my ($self) = @_; $self->end_element while @{$self->{_stack}}; print {$self->fh} "\n"; } 1; __END__ =head1 NAME XML::Struct::Writer::Stream - simplified SAX handler to serialize (Micro)XML =head1 DESCRIPTION This class implements a simplfied SAX handler for stream-based serialization of XML. DTDs, comments, processing instructions and similar features not part of MicroXML are not supported. The handler is written to reproduce the serialization of libxml. =head1 CONFIGURATION =over =item fh File handle or compatible object to write to (standard output by default). =item pretty Pretty-print XML if enabled. =back =head1 SEE ALSO See L, L, and L for more elaborated SAX writers and L for a general XML writer, not based on SAX. =cut XML-Struct-0.26/lib/XML/Struct/Writer.pm0000644000175000017500000002366412535515543016070 0ustar vojvojpackage XML::Struct::Writer; use strict; use Moo; use XML::LibXML::SAX::Builder; use XML::Struct::Writer::Stream; use Scalar::Util qw(blessed reftype); use Carp; our $VERSION = '0.26'; has attributes => (is => 'rw', default => sub { 1 }); has encoding => (is => 'rw', default => sub { 'UTF-8' }); has version => (is => 'rw', default => sub { '1.0' }); has standalone => (is => 'rw'); has pretty => (is => 'rw', default => sub { 0 }); # 0|1|2 has xmldecl => (is => 'rw', default => sub { 1 }); has handler => (is => 'lazy', builder => 1); has to => ( is => 'rw', coerce => sub { if (!ref $_[0]) { return IO::File->new($_[0], 'w'); } elsif (reftype($_[0]) eq 'SCALAR') { open my $io,">:utf8",$_[0]; return $io; } else { # IO::Handle, GLOB, ... return $_[0]; } }, trigger => sub { delete $_[0]->{handler} } ); sub _build_handler { $_[0]->to ? XML::Struct::Writer::Stream->new( fh => $_[0]->to, encoding => $_[0]->encoding, version => $_[0]->version, pretty => $_[0]->pretty, ) : XML::LibXML::SAX::Builder->new( handler => $_[0] ); } sub write { my ($self, $element, $name) = @_; $self->writeStart; $self->writeElement( $self->microXML($element, $name // 'root') ); $self->writeEnd; $self->handler->can('result') ? $self->handler->result : 1; } *writeDocument = \&write; # TODO: Make available as function in XML::Struct or XML::Struct::Simple sub microXML { my ($self, $element, $name) = @_; my $type = reftype($element); if ($type) { # MicroXML if ($type eq 'ARRAY') { if (@$element == 1) { return $element; } elsif (@$element == 2) { if ( (reftype($element->[1]) // '') eq 'ARRAY') { return [ $element->[0], {}, $element->[1] ]; } elsif (!$self->attributes and %{$element->[1]}) { return [ $element->[0] ]; } else { return $element; } } else { if (!$self->attributes and %{$element->[1]}) { return [ $element->[0], {}, $element->[2] ]; } else { return $element; } } # SimpleXML } elsif ($type eq 'HASH') { my $children = [ map { my ($tag, $content) = ($_, $element->{$_}); # text if (!ref $content) { [ $tag, {}, [$content] ] } elsif (reftype($content) eq 'ARRAY') { @$content ? map { [ $tag, {}, [$_] ] } @$content : [ $tag ]; } elsif (reftype $content eq 'HASH' ) { [ $tag, {}, [ $content ] ]; } else { (); } } grep { defined $element->{$_} } sort keys %$element ]; return $name ? [ $name, {}, $children ] : @$children; } } croak "expected XML as ARRAY or HASH reference"; } sub writeElement { my $self = shift; foreach my $element (@_) { $self->writeStartElement($element); foreach my $child ( @{ $element->[2] // [] } ) { if (ref $child) { $self->writeElement( $self->microXML($child) ); } else { $self->writeCharacters($child); } } $self->writeEndElement($element); } } sub writeStartElement { my ($self, $element) = @_; my $args = { Name => $element->[0] }; $args->{Attributes} = $element->[1] if $element->[1]; $self->handler->start_element($args); } sub writeEndElement { my ($self, $element) = @_; $self->handler->end_element({ Name => $element->[0] }); } sub writeCharacters { $_[0]->handler->characters({ Data => $_[1] }); } sub writeStart { my $self = shift; $self->handler->start_document; if ($self->handler->can('xml_decl') && $self->xmldecl) { $self->handler->xml_decl({ Version => $self->version, Encoding => $self->encoding, Standalone => $self->standalone, }); } $self->writeStartElement(@_) if @_; } sub writeEnd { my $self = shift; $self->writeEndElement(@_) if @_; $self->handler->end_document; } 1; __END__ =encoding UTF-8 =head1 NAME XML::Struct::Writer - Write XML data structures to XML streams =head1 SYNOPSIS use XML::Struct::Writer; # serialize XML::Struct::Writer->new( to => \*STDOUT, attributes => 0, pretty => 1, )->write( [ doc => [ [ name => [ "alice" ] ], [ name => [ "bob" ] ], ] ] ); # # # alice # bob # # create DOM my $xml = XML::Struct::Writer->new->write( [ greet => { }, [ "Hello, ", [ emph => { color => "blue" } , [ "World" ] ], "!" ] ] ); $xml->toFile("greet.xml"); # # Hello, World! =head1 DESCRIPTION This module writes an XML document, given as L data structure, as stream of L. The default handler receives these events with L to build a DOM tree which can then be used to serialize the XML document as string. The writer can also be used to directly serialize XML with L. L provides the shortcut function C to this module. XML elements can be passed in any of these forms and its combinations: # MicroXML: [ $name => \%attributes, \@children ] [ $name => \%attributes ] [ $name ] # lax MicroXML also: [ $name => \@children ] # SimpleXML: { $name => \@children, $name => $content, ... } =head1 CONFIGURATION A XML::Struct::Writer can be configured with the following options: =over =item to Filename, L, string reference, or other kind of stream to directly serialize XML to with L. This option is ignored if C is explicitly set. =item handler A SAX handler to send L to. If neither this option nor C is explicitly set, an instance of L is used to build a DOM. =item attributes Ignore XML attributes if set to false. Set to true by default. =item xmldecl Include XML declaration on serialization. Enabled by default. =item encoding An encoding (for handlers that support an explicit encoding). Set to UTF-8 by default. =item version The XML version. Set to C<1.0> by default. =item standalone Add standalone flag in the XML declaration. =item pretty Pretty-print XML. Disabled by default. =back =head1 METHODS =head2 write( $root [, $name ] ) == writeDocument( $root [, $name ] ) Write an XML document, given as array reference (lax MicroXML), hash reference (SimpleXML), or both mixed. If given as hash reference, the name of a root tag can be chosen or it is set to C. This method is basically equivalent to: $writer->writeStart; $writer->writeElement( $writer->microXML($root, $name // 'root') ); $writer->writeEnd; $writer->result if $writer->can('result'); The remaining methods expect XML in MicroXML format only. =head2 writeElement( $element [, @more_elements ] ) Write one or more XML elements and their child elements to the handler. =head2 writeStart( [ $root [, $name ] ] ) Call the handler's C and C methods. An optional root element can be passed, so C<< $writer->writeStart($root) >> is equivalent to: $writer->writeStart; $writer->writeStartElement($root); =head2 writeStartElement( $element ) Directly call the handler's C method. =head2 writeEndElement( $element ) Directly call the handler's C method. =head2 writeCharacters( $string ) Directy call the handler's C method. =head2 writeEnd( [ $root ] ) Directly call the handler's C method. An optional root element can be passed, so C<< $writer->writeEnd($root) >> is equivalent to: $writer->writeEndElement($root); $writer->writeEnd; =head2 microXML( $element [, $name ] ) Convert an XML element, given as array reference (lax MicroXML) or as hash reference (SimpleXML) to a list of MicroXML elements and optionally remove attributes. Does not affect child elements. =head1 SAX EVENTS A SAX handler, set with option C, is expected to implement the following methods (two of them are optional): =over =item xml_decl( { Version => $version, Encoding => $encoding } ) Optionally called once at the start of an XML document, if the handler supports this method. =item start_document() Called once at the start of an XML document. =item start_element( { Name => $name, Attributes => \%attributes } ) Called at the start of an XML element to emit an XML start tag. =item end_element( { Name => $name } ) Called at the end of an XML element to emit an XML end tag. =item characters( { Data => $characters } ) Called for character data. Character entities and CDATA section are expanded to strings. =item end_document() Called once at the end of an XML document. =item result() Optionally called at the end of C/C to return a value from this methods. Handlers do not need to implement this method. =back =head1 SEE ALSO Using a streaming SAX handler, such as L, L, L, and possibly L should be more performant for serialization. Examples of other modules that receive SAX events include L, L, and L, =cut XML-Struct-0.26/dist.ini0000644000175000017500000000003312535515543013211 0ustar vojvojauthor=Jakob Voß [@Milla] XML-Struct-0.26/MANIFEST0000644000175000017500000000066512535515543012711 0ustar vojvoj# This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.020. Build.PL Changes LICENSE MANIFEST META.json META.yml README cpanfile dist.ini lib/XML/Struct.pm lib/XML/Struct/Reader.pm lib/XML/Struct/Simple.pm lib/XML/Struct/Writer.pm lib/XML/Struct/Writer/Stream.pm t/flat.xml t/issue-10.t t/nested.xml t/reader-depth.t t/reader-path.t t/reader.t t/release-pod-syntax.t t/simple.t t/struct.t t/write-mixed.t t/writer.t