MyXML.pm

filter: Statementstmt 88.9% 274 / 308 Branchbran 64.5% 111 / 172 Conditioncond 60.0% 36 / 60 MC/DCmcdc 37.1% 13 / 35 Subroutinesub 92.3% 24 / 26 Podpod 100% 7 / 7 totaltotal 76.4% 465 / 608 CC 122 SCAR 31.8
CC
122
Cov
78%
_objectarray_to_simple_arrayref
110.0
xml_to_object
39.8
simple_to_xml
24.1
CRAP 24.0
↑ Summary MyXML/Object.pm »
1 package XML::MyXML;
2  
3 5 ▶use 5.008001;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 5 ▶use XML::MyXML::Object;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use XML::MyXML::Util 'trim', 'strip_ns';
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 5 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 5 ▶use Scalar::Util 'weaken';
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 5 require Exporter;
15 5 our @ISA = qw(Exporter);
16 5 our @EXPORT_OK = qw(tidy_xml object_to_xml xml_to_object simple_to_xml xml_to_simple check_xml xml_escape);
17 5 our %EXPORT_TAGS = (all => [@EXPORT_OK]);
18  
19 5 our $VERSION = "1.09";
20  
21 5 my $DEFAULT_INDENTSTRING = ' ' x 4;
22  
23  
24 =encoding utf-8
25  
26 =head1 NAME
27  
28 XML::MyXML - A simple-to-use XML module, for parsing and creating XML documents
29  
30 =head1 SYNOPSIS
31  
32 use XML::MyXML qw(tidy_xml xml_to_object);
33 use XML::MyXML qw(:all);
34  
35 my $xml = "<item><name>Table</name><price><usd>10.00</usd><eur>8.50</eur></price></item>";
36 print tidy_xml($xml);
37  
38 my $obj = xml_to_object($xml);
39 print "Price in Euros = " . $obj->path('price/eur')->text;
40  
41 $obj->simplify is hashref { item => { name => 'Table', price => { usd => '10.00', eur => '8.50' } } }
42 $obj->simplify({ internal => 1 }) is hashref { name => 'Table', price => { usd => '10.00', eur => '8.50' } }
43  
44 =head1 EXPORTABLE
45  
46 xml_escape, tidy_xml, xml_to_object, object_to_xml, simple_to_xml, xml_to_simple, check_xml
47  
48 =head1 FEATURES & LIMITATIONS
49  
50 This module can parse XML comments, CDATA sections, XML entities (the standard five and numeric ones) and
51 simple non-recursive C<< <!ENTITY> >>s
52  
53 It will ignore (won't parse) C<< <!DOCTYPE...> >>, C<< <?...?> >> and other C<< <!...> >> special markup
54  
55 All strings (XML documents, attribute names, values, etc) produced by this module or passed as parameters
56 to its functions, are strings that contain characters, rather than bytes/octets. Unless you use the C<bytes>
57 function flag (see below), in which case the XML documents (and just the XML documents) will be byte/octet
58 strings.
59  
60 XML documents to be parsed may not contain the C<< > >> character unencoded in attribute values
61  
62 =head1 OPTIONAL FUNCTION FLAGS
63  
64 Some functions and methods in this module accept optional flags, listed under each function in the
65 documentation. They are optional, default to zero unless stated otherwise, and can be used as follows:
66 S<C<< function_name( $param1, { flag1 => 1, flag2 => 1 } ) >>>. This is what each flag does:
67  
68 C<strip> : the function will strip initial and ending whitespace from all text values returned
69  
70 C<file> : the function will expect the path to a file containing an XML document to parse, instead of an
71 XML string
72  
73 C<complete> : the function's XML output will include an XML declaration (C<< <?xml ... ?> >>) in the
74 beginning
75  
76 C<internal> : the function will only return the contents of an element in a hashref instead of the
77 element itself (see L</SYNOPSIS> for example)
78  
79 C<tidy> : the function will return tidy XML
80  
81 C<indentstring> : when producing tidy XML, this denotes the string with which child elements will be
82 indented (Default is a string of 4 spaces)
83  
84 C<save> : the function (apart from doing what it's supposed to do) will also save its XML output in a
85 file whose path is denoted by this flag
86  
87 C<strip_ns> : strip the namespaces (characters up to and including ':') from the tags
88  
89 C<xslt> : will add a <?xml-stylesheet?> link in the XML that's being output, of type 'text/xsl',
90 pointing to the filename or URL denoted by this flag
91  
92 C<arrayref> : the function will create a simple arrayref instead of a simple hashref (which will preserve
93 order and elements with duplicate tags)
94  
95 C<bytes> : the XML document string which is parsed and/or produced by this function, should contain
96 bytes/octets rather than characters
97  
98 =head1 FUNCTIONS
99  
100 =cut
101  
102 91 ▶sub _encode {
Subroutine _encode: called CC=2 SCAR=7.0
103 91 my $string = shift;
104 91 ▶ defined $string or $string = '';
Branch: 1 branch
BranchTrueFalseTotal
defined $string or $string = "" 91 0 91
105 91 my %replace = (
106 '<' => '&lt;',
107 '>' => '&gt;',
108 '&' => '&amp;',
109 '\'' => '&apos;',
110 '"' => '&quot;',
111 );
112 91 my $keys = "(".join("|", sort {length($b) <=> length($a)} keys %replace).")";
113 91 $string =~ s/$keys/$replace{$1}/g;
114 91 return $string;
115 }
116  
117  
118 =head2 xml_escape($string)
119  
120 Returns the same string, but with the C<< < >>, C<< > >>, C<< & >>, C<< " >> and C<< ' >> characters
121 replaced by their XML entities (e.g. C<< &amp; >>).
122  
123 =cut
124  
125 1 ▶sub xml_escape {
Subroutine xml_escape: called CC=1 SCAR=0.0
Pod documented
126 1 my ($string) = @_;
127  
128 1 return _encode($string);
129 }
130  
131 186 ▶sub _decode {
Subroutine _decode: called CC=6 SCAR=18.0
132 186 my $string = shift;
133 186 ▶ my $entities = shift || {};
Condition100%2/2
shift() || {}
l!l
1815
MC/DC100%1/1
shift() || {}
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
134 186 ▶ my $flags = shift || {};
Condition50%1/2
shift() || {}
l!l
0186
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
135 186 ▶ defined $string or $string = '';
Branch: 1 branch
BranchTrueFalseTotal
defined $string or $string = "" 186 0 186
136 186 my %replace = (
137 %$entities,
138 '&lt;' => '<',
139 '&gt;' => '>',
140 '&amp;' => '&',
141 '&apos;' => "'",
142 '&quot;' => '"',
143 );
144 186 my @capture = map quotemeta, keys %replace;
145 186 push @capture, '\&\#x([0-9A-Fa-f]+)\;', '\&\#([0-9]+)\;';
146 186 my $capture = "(".join("|", @capture).")";
147 186 $string =~ s|
148 $capture
149 |
150 10 my $reference = $1;
151 10 my $hex = $2;
152 10 my $decimal = $3;
153 $reference =~ /\&\#x/ ? chr(hex($hex))
154 : $reference =~ /\&\#/ ? chr($decimal)
155 10 ▶ : $replace{$reference};
Branch: 2 branches
BranchTrueFalseTotal
$reference =~ /\&\#x/ ? : 2 8 10
$reference =~ /\&\#/ ? : 1 7 8
156 |gex;
157 186 return $string;
158 }
159  
160  
161 =head2 tidy_xml($raw_xml)
162  
163 Returns the XML string in a tidy format (with tabs & newlines)
164  
165 Optional flags: C<file>, C<complete>, C<indentstring>, C<save>, C<bytes>
166  
167 =cut
168  
169 3 ▶sub tidy_xml {
Subroutine tidy_xml: called CC=3 SCAR=11.2
Pod documented
170 3 my $xml = shift;
171 3 ▶ my $flags = shift || {};
Condition50%1/2
shift() || {}
l!l
30
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
172  
173 3 my $object = xml_to_object($xml, $flags);
174 3 ▶ defined $object or return $object;
Branch: 1 branch
BranchTrueFalseTotal
defined $object or return $object 3 0 3
175 3 _tidy_object($object, undef, $flags);
176 3 my $return = $object->to_xml({ %$flags, tidy => 0 }) . "\n";
177 3 return $return;
178 }
179  
180  
181 =head2 xml_to_object($raw_xml)
182  
183 Creates an 'XML::MyXML::Object' object from the raw XML provided
184  
185 Optional flags: C<file>, C<bytes>
186  
187 =cut
188  
189 43 ▶sub xml_to_object {
Subroutine xml_to_object: called CC=34 SCAR=36.8
Pod documented
190 43 my $xml = shift;
191 43 ▶ my $flags = shift || {};
Condition100%2/2
shift() || {}
l!l
1825
MC/DC100%1/1
shift() || {}
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
192  
193 43 ▶ if ($flags->{file}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags->{"file"}) 1 42 43
194 1 ▶ open my $fh, '<', $xml or croak "Error: The file '$xml' could not be opened for reading: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $xml or croak("Error: The file '${xml}' could not be opened for reading: $!") 1 0 1
195 1 $xml = do { local $/; <$fh> };
196 1 close $fh;
197 }
198  
199 43 ▶ if ($flags->{bytes} or $flags->{file}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags->{"bytes"} or $flags->{"file"}) 5 38 43
Condition100%3/3
$flags->{"bytes"} or $flags->{"file"}
l!l&&r!l&&!r
4138
MC/DC100%2/2
$flags->{"bytes"} or $flags->{"file"}
$flags->{"bytes"} $flags->{"file"}
Truth table100%3/3
A or B
A= $flags->{"bytes"}B= $flags->{"file"}
ABresult
1X1
011
000
200 5 my (undef, undef, $encoding) = $xml =~ /<\?xml(\s[^>]+)?\sencoding=(['"])(.*?)\2/;
201 5 ▶ $encoding = 'UTF-8' if ! defined $encoding or $encoding =~ /^utf\-?8\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $encoding or $encoding =~ /^utf\-?8\z/i 5 0 5
Condition33%1/3
not defined $encoding or $encoding =~ /^utf\-?8\z/i
l!l&&r!l&&!r
500
MC/DC0%0/2
not defined $encoding or $encoding =~ /^utf\-?8\z/i
not defined $encoding $encoding =~ /^utf\-?8\z/i
Truth table33%1/3
not(A) or B
A= not defined $encodingB= $encoding =~ /^utf\-?8\z/i
ABresult
1X1
011
000
202 5 ▶ my $encoding_obj = find_encoding($encoding) or croak "Error: encoding '$encoding' not found";
Branch: 1 branch
BranchTrueFalseTotal
my $encoding_obj = &find_encoding($encoding) or croak("Error: encoding '${encoding}' not found") 5 0 5
203 5 ▶ eval { $xml = $encoding_obj->decode($xml, Encode::FB_CROAK); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $xml = $encoding_obj->decode($xml, 1); 1 } } or croak("Error: Input string is invalid $encoding") 4 1 5
204 or croak "Error: Input string is invalid $encoding";
205 }
206  
207 42 my $entities = {};
208  
209 # Parse CDATA sections
210 0 $xml =~ s/\<\!\[CDATA\[(.*?)\]\]\>/_encode($1)/egs;
211 42 my @items = $xml =~ /(<!--.*?(?:-->|$)|<[^>]*?>|[^<>]+)/sg;
212 # Remove comments, special markup and initial whitespace
213 {
214 42 my $init_ws = 1; # whether we are inside initial whitespace
215 42 foreach my $item (@items) {
216 373 ▶ if ($item =~ /\A<!--/) {
Branch: 5 branches
BranchTrueFalseTotal
if ($item =~ /\A<!--/) { } 0 373 373
elsif ($item =~ /\A<\?/) { } 1 372 373
elsif (my($entname, undef, $entvalue) = $item =~ /^<!ENTITY\s+(\S+)\s+(['"])(.*?)\2\s*>\z/) { } 2 370 372
elsif ($item =~ /<!/) { } 0 370 370
elsif ($init_ws) { } 46 324 370
217 0 ▶ if ($item !~ /-->\z/) { croak encode_utf8("Error: unclosed XML comment block - '$item'"); }
Branch: 1 branch
BranchTrueFalseTotal
unless ($item =~ /-->\z/) 0 0 0
218 0 undef $item;
219 } elsif ($item =~ /\A<\?/) { # like <?xml?> or <?target?>
220 0 ▶ if ($item !~ /\?>\z/) { croak encode_utf8("Error: Erroneous special markup - '$item'"); }
Branch: 1 branch
BranchTrueFalseTotal
unless ($item =~ /\?>\z/) 0 1 1
221 1 undef $item;
222 } elsif (my ($entname, undef, $entvalue) = $item =~ /^<!ENTITY\s+(\S+)\s+(['"])(.*?)\2\s*>\z/) {
223 2 $entities->{"&$entname;"} = _decode($entvalue);
224 2 undef $item;
225 } elsif ($item =~ /<!/) { # like <!DOCTYPE> or <!ELEMENT> or <!ATTLIST>
226 0 undef $item;
227 } elsif ($init_ws) {
228 46 ▶ if ($item =~ /\S/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($item =~ /\S/) { } 42 4 46
229 42 $init_ws = 0;
230 } else {
231 4 undef $item;
232 }
233 }
234 }
235 42 ▶ @items = grep defined, @items or croak "Error: No elements in the XML document";
Branch: 1 branch
BranchTrueFalseTotal
@items = grep(defined($_), @items) or croak("Error: No elements in the XML document") 42 0 42
236 }
237 42 my @stack;
238 42 my $object = bless ({
239 content => [],
240 full_ns_info => {},
241 ns_data => {},
242 }, 'XML::MyXML::Object');
243 42 my $pointer = $object;
244 42 foreach my $item (@items) {
245 366 ▶ if ($item =~ /^\<\/?\>\z/) {
Branch: 4 branches
BranchTrueFalseTotal
if ($item =~ m[^\</?\>\z]) { } 0 366 366
elsif ($item =~ m[^\</([^\s>]+)\>\z]) { } 113 253 366
elsif ($item =~ m[^\<[^>]+?(/)?\>\z]) { } 124 129 253
elsif ($item =~ /^[^<>]*\z/) { } 129 0 129
246 0 croak encode_utf8("Error: Strange tag: '$item'");
247 } elsif ($item =~ /^\<\/([^\s>]+)\>\z/) {
248 113 my ($el_name) = $1;
249 113 ▶ $stack[-1]{el_name} eq $el_name
Branch: 1 branch
BranchTrueFalseTotal
$stack[-1]{"el_name"} eq $el_name or croak(&encode_utf8(qq[Error: Incompatible stack element: stack='$stack[-1]{"el_name"}' item='${item}'])) 113 0 113
250 or croak encode_utf8("Error: Incompatible stack element: stack='$stack[-1]{el_name}' item='$item'");
251 113 my $stack_entry = pop @stack;
252 113 ▶ delete $stack_entry->{content} if ! @{$stack_entry->{content}};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$stack_entry->{"content"};} 1 112 113
253 113 $pointer = $stack_entry->{parent};
254 } elsif ($item =~ /^\<[^>]+?(\/)?\>\z/) {
255 124 my $is_self_closing = defined $1;
256 124 my ($el_name) = $item =~ /^<([^\s>\/]+)/;
257 124 ▶ defined $el_name or croak encode_utf8("Error: Strange tag: '$item'");
Branch: 1 branch
BranchTrueFalseTotal
defined $el_name or croak(&encode_utf8("Error: Strange tag: '${item}'")) 124 0 124
258 124 $item =~ s/^\<\Q$el_name\E//;
259 124 $item =~ s/\/>\z//;
260 124 my @attrs = $item =~ /\s+(\S+=(['"]).*?\2)/g;
261 124 my $i = 0;
262 124 @attrs = grep {++$i % 2} @attrs;
263 124 my %attr;
264 124 foreach my $attr (@attrs) {
265 52 my ($attr_name, undef, $attr_value) = $attr =~ /^(\S+?)=(['"])(.*?)\2\z/;
266 52 ▶ defined $attr_name or croak encode_utf8("Error: Strange attribute: '$attr'");
Branch: 1 branch
BranchTrueFalseTotal
defined $attr_name or croak(&encode_utf8("Error: Strange attribute: '${attr}'")) 52 0 52
267 52 $attr{$attr_name} = _decode($attr_value, $entities);
268 }
269 124 ▶ my $entry = bless {
Branch: 1 branch
BranchTrueFalseTotal
$is_self_closing ? : 10 114 124
270 el_name => $el_name,
271 attrs => \%attr,
272 $is_self_closing ? () : (content => []),
273 parent => $pointer,
274 }, 'XML::MyXML::Object';
275 124 weaken $entry->{parent};
276 124 $entry->_apply_namespace_declarations;
277 124 ▶ push @stack, $entry unless $is_self_closing;
Branch: 1 branch
BranchTrueFalseTotal
unless $is_self_closing 114 10 124
278 124 push @{$pointer->{content}}, $entry;
279 124 ▶ $pointer = $entry unless $is_self_closing;
Branch: 1 branch
BranchTrueFalseTotal
unless $is_self_closing 114 10 124
280 } elsif ($item =~ /^[^<>]*\z/) {
281 129 my $entry = bless {
282 text => _decode($item, $entities),
283 parent => $pointer,
284 }, 'XML::MyXML::Object';
285 129 weaken $entry->{parent};
286 129 push @{$pointer->{content}}, $entry;
287 } else {
288 0 croak encode_utf8("Error: Strange element: '$item'");
289 }
290 }
291 42 ▶ ! @stack or croak encode_utf8("Error: The <$stack[-1]{el_name}> element has not been closed in the XML document");
Branch: 1 branch
BranchTrueFalseTotal
@stack and croak(&encode_utf8(qq[Error: The <$stack[-1]{"el_name"}> element has not been closed in the XML document])) 1 41 42
292 41 $object = $object->{content}[0];
293 41 $object->{parent} = undef;
294 41 return $object;
295 }
296  
297 60 ▶sub _objectarray_to_xml {
Subroutine _objectarray_to_xml: called CC=7 SCAR=19.5
298 60 my $object = shift;
299  
300 60 my $xml = '';
301 60 foreach my $stuff (@$object) {
302 78 ▶ if (! defined $stuff->{el_name} and defined $stuff->{text}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $stuff->{'el_name'} and defined $stuff->{'text'}) { } 32 46 78
Condition66%2/3
not defined $stuff->{"el_name"} and defined $stuff->{"text"}
!ll&&!rl&&r
46032
MC/DC50%1/2
not defined $stuff->{"el_name"} and defined $stuff->{"text"}
not defined $stuff->{"el_name"} defined $stuff->{"text"}
Truth table66%2/3
not(A) and B
A= not defined $stuff->{"el_name"}B= defined $stuff->{"text"}
ABresult
0X0
100
111
303 32 $xml .= _encode($stuff->{text});
304 } else {
305 46 $xml .= "<".$stuff->{el_name};
306 46 foreach my $attrname (keys %{$stuff->{attrs}}) {
307 1 $xml .= " ".$attrname.'="'._encode($stuff->{attrs}{$attrname}).'"';
308 }
309 46 ▶ if (! defined $stuff->{content} or ! @{ $stuff->{content} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $stuff->{'content'} && @{$stuff->{'content'};}) { } 7 39 46
Condition66%2/3
defined $stuff->{'content'} && @{$stuff->{'content'};}
!ll&&!rl&&r
0739
MC/DC50%1/2
defined $stuff->{'content'} && @{$stuff->{'content'};}
defined $stuff->{'content'} @{$stuff->{'content'};}
Truth table66%2/3
A && B
A= defined $stuff->{'content'}B= @{$stuff->{'content'};}
ABresult
0X0
100
111
310 7 $xml .= "/>"
311 } else {
312 39 $xml .= ">";
313 39 $xml .= _objectarray_to_xml($stuff->{content});
314 39 $xml .= "</".$stuff->{el_name}.">";
315 }
316 }
317 }
318 60 return $xml;
319 }
320  
321  
322 =head2 object_to_xml($object)
323  
324 Creates an XML string from the 'XML::MyXML::Object' object provided
325  
326 Optional flags: C<complete>, C<tidy>, C<indentstring>, C<save>, C<bytes>
327  
328 =cut
329  
330 0 ▶sub object_to_xml {
Subroutine object_to_xml: not called CC=2 SCAR=17.9
Pod documented
331 0 my $object = shift;
332 0 ▶ my $flags = shift || {};
Condition0%0/2
shift() || {}
l!l
00
MC/DC0%0/1
shift() || {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
333  
334 0 return $object->to_xml( $flags );
335 }
336  
337 19 ▶sub _tidy_object {
Subroutine _tidy_object: called CC=13 SCAR=25.7
338 19 my $object = shift;
339 19 ▶ my $tabs = shift || 0;
Condition100%2/2
shift() || 0
l!l
163
MC/DC100%1/1
shift() || 0
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
340 19 ▶ my $flags = shift || {};
Condition50%1/2
shift() || {}
l!l
190
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
341  
342 19 ▶ my $indentstring = exists $flags->{indentstring} ? $flags->{indentstring} : $DEFAULT_INDENTSTRING;
Branch: 1 branch
BranchTrueFalseTotal
exists $flags->{'indentstring'} ? : 11 8 19
343  
344 19 ▶ return unless defined $object->{content} and @{$object->{content}};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $object->{"content"} and @{$object->{"content"};} 10 9 19
Condition66%2/3
defined $object->{"content"} and @{$object->{"content"};}
!ll&&!rl&&r
1009
MC/DC50%1/2
defined $object->{"content"} and @{$object->{"content"};}
defined $object->{"content"} @{$object->{"content"};}
Truth table66%2/3
A and B
A= defined $object->{"content"}B= @{$object->{"content"};}
ABresult
0X0
100
111
345 9 my $hastext;
346 9 my @children = @{$object->{content}};
347 9 foreach my $i (0..$#children) {
348 11 my $child = $children[$i];
349 11 ▶ if (defined $child->{text} and $child->{text} =~ /\S/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $child->{"text"} and $child->{"text"} =~ /\S/) 5 6 11
Condition66%2/3
defined $child->{"text"} and $child->{"text"} =~ /\S/
!ll&&!rl&&r
605
MC/DC50%1/2
defined $child->{"text"} and $child->{"text"} =~ /\S/
defined $child->{"text"} $child->{"text"} =~ /\S/
Truth table66%2/3
A and B
A= defined $child->{"text"}B= $child->{"text"} =~ /\S/
ABresult
0X0
100
111
350 5 $hastext = 1;
351 5 last;
352 }
353 }
354 9 ▶ return if $hastext;
Branch: 1 branch
BranchTrueFalseTotal
if $hastext 5 4 9
355  
356 4 ▶ @{$object->{content}} = grep { ! defined $_->{text} or $_->{text} =~ /\S/ } @{$object->{content}};
Condition33%1/3
!defined($_->{'text'}) || $_->{'text'} =~ /\S/
l!l&&r!l&&!r
600
MC/DC0%0/2
!defined($_->{'text'}) || $_->{'text'} =~ /\S/
!defined($_->{'text'}) $_->{'text'} =~ /\S/
Truth table33%1/3
not(A) || B
A= !defined($_->{'text'})B= $_->{'text'} =~ /\S/
ABresult
1X1
011
000
357  
358 4 @children = @{$object->{content}};
359 4 $object->{content} = [];
360 4 for my $i (0..$#children) {
361 6 my $whitespace = bless {
362 text => "\n".($indentstring x ($tabs+1)),
363 parent => $object,
364 }, 'XML::MyXML::Object';
365 6 weaken $whitespace->{parent};
366 6 push @{$object->{content}}, $whitespace;
367 6 push @{$object->{content}}, $children[$i];
368 }
369 4 my $whitespace = bless {
370 text => "\n".($indentstring x $tabs),
371 parent => $object,
372 }, 'XML::MyXML::Object';
373 4 weaken $whitespace->{parent};
374 4 push @{$object->{content}}, $whitespace;
375  
376 4 for my $i (0..$#{$object->{content}}) {
377 16 _tidy_object($object->{content}[$i], $tabs+1, $flags);
378 }
379 }
380  
381  
382 =head2 simple_to_xml($simple_array_ref)
383  
384 Produces a raw XML string from either an array reference, a hash reference or a mixed structure such as these examples:
385  
386 { thing => { name => 'John', location => { city => 'New York', country => 'U.S.A.' } } }
387 # <thing><name>John</name><location><country>U.S.A.</country><city>New York</city></location></thing>
388  
389 [ thing => [ name => 'John', location => [ city => 'New York', country => 'U.S.A.' ] ] ]
390 # <thing><name>John</name><location><country>U.S.A.</country><city>New York</city></location></thing>
391  
392 { thing => { name => 'John', location => [ city => 'New York', city => 'Boston', country => 'U.S.A.' ] } }
393 # <thing><name>John</name><location><city>New York</city><city>Boston</city><country>U.S.A.</country></location></thing>
394  
395 Here's a mini-tutorial on how to use this function, in which you'll also see how to set attributes.
396  
397 The simplest invocations are these:
398  
399 simple_to_xml({target => undef})
400 # <target/>
401  
402 simple_to_xml({target => 123})
403 # <target>123</target>
404  
405 Every set of sibling elements (such as the document itself, which is a single top-level element, or a pack of
406 5 elements all children to the same parent element) is represented in the $simple_array_ref parameter as
407 key-value pairs inside either a hashref or an arrayref (you can choose which).
408  
409 Keys represent tags+attributes of the sibling elements, whereas values represent the contents of those elements.
410  
411 Eg:
412  
413 [
414 first => 'John',
415 last => 'Doe,'
416 ]
417  
418 ...and...
419  
420 {
421 first => 'John',
422 last => 'Doe',
423 }
424  
425 both translate to:
426  
427 <first>John</first><last>Doe</last>
428  
429 A value can either be undef (to denote an empty element), or a string (to denote a string), or another
430 hashref/arrayref to denote a set of children elements, like this:
431  
432 {
433 person => {
434 name => {
435 first => 'John',
436 last => 'Doe'
437 }
438 }
439 }
440  
441 ...becomes:
442  
443 <person>
444 <name>
445 <first>John</first>
446 <last>Doe</last>
447 </name>
448 </person>
449  
450  
451 The only difference between using an arrayref or using a hashref, is that arrayrefs preserve the
452 order of the elements, and allow repetition of identical tags. So a person with many addresses, should choose to
453 represent its list of addresses under an arrayref, like this:
454  
455 {
456 person => [
457 name => {
458 first => 'John',
459 last => 'Doe',
460 },
461 address => {
462 country => 'Malta',
463 },
464 address => {
465 country => 'Indonesia',
466 },
467 address => {
468 country => 'China',
469 }
470 ]
471 }
472  
473 ...which becomes:
474  
475 <person>
476 <name>
477 <last>Doe</last>
478 <first>John</first>
479 </name>
480 <address>
481 <country>Malta</country>
482 </address>
483 <address>
484 <country>Indonesia</country>
485 </address>
486 <address>
487 <country>China</country>
488 </address>
489 </person>
490  
491 Finally, to set attributes to your elements (eg id="12") you need to replace the key with either
492 a string containing attributes as well (eg: C<'address id="12"'>), or replace it with a reference, as the many
493 items in the examples below:
494  
495 {thing => [
496 'item id="1"' => 'chair',
497 [item => {id => 2}] => 'table',
498 [item => [id => 3]] => 'door',
499 [item => id => 4] => 'sofa',
500 {item => {id => 5}} => 'bed',
501 {item => [id => 6]} => 'shirt',
502 [item => {id => 7, other => 8}, [more => 9, also => 10, but_not => undef]] => 'towel'
503 ]}
504  
505 ...which becomes:
506  
507 <thing>
508 <item id="1">chair</item>
509 <item id="2">table</item>
510 <item id="3">door</item>
511 <item id="4">sofa</item>
512 <item id="5">bed</item>
513 <item id="6">shirt</item>
514 <item id="7" other="8" more="9" also="10">towel</item>
515 </thing>
516  
517 As you see, attributes may be represented in a great variety of ways, so you don't need to remember
518 the "correct" one.
519  
520 Of course if the "simple structure" is a hashref, the key cannot be a reference (because hash keys are always
521 strings), so if you want attributes on your elements, you either need the enclosing structure to be an
522 arrayref as in the example above, to allow keys to be refs which contain the attributes, or you need to
523 represent the key (=tag+attrs) as a string, like this (also in the previous example): C<'item id="1"'>
524  
525 This concludes the mini-tutorial of the simple_to_xml function.
526  
527 All the strings in C<$simple_array_ref> need to contain characters, rather than bytes/octets. The C<bytes>
528 optional flag only affects the produced XML string.
529  
530 Optional flags: C<complete>, C<tidy>, C<indentstring>, C<save>, C<xslt>, C<bytes>
531  
532 =cut
533  
534 21 ▶sub simple_to_xml {
Subroutine simple_to_xml: called CC=17 SCAR=31.8
Pod documented
535 21 my $arref = shift;
536 21 ▶ my $flags = shift || {};
Condition100%2/2
shift() || {}
l!l
219
MC/DC100%1/1
shift() || {}
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
537  
538 21 my $xml = '';
539 21 ▶ my ($key, $value, @residue) = (ref $arref eq 'HASH') ? %$arref : @$arref;
Branch: 1 branch
BranchTrueFalseTotal
ref $arref eq 'HASH' ? : 9 12 21
540 21 $key = _key_to_string($key);
541 21 ▶ ! @residue or croak "Error: the provided simple ref contains more than 1 top element";
Branch: 1 branch
BranchTrueFalseTotal
@residue and croak("Error: the provided simple ref contains more than 1 top element") 0 21 21
542 21 my ($el_name) = $key =~ /^(\S+)/;
543 21 ▶ defined $el_name or croak encode_utf8 "Error: Strange key: $key";
Branch: 1 branch
BranchTrueFalseTotal
defined $el_name or croak(&encode_utf8("Error: Strange key: $key")) 21 0 21
544  
545 21 ▶ if (! ref $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $value) { } 12 9 21
546 12 ▶ if ($key eq '!as_is') {
Branch: 2 branches
BranchTrueFalseTotal
if ($key eq '!as_is') { } 0 12 12
elsif (defined $value and length $value) { } 12 0 12
547 0 ▶ check_xml $value or croak "invalid xml: $value";
Branch: 1 branch
BranchTrueFalseTotal
$value->check_xml or croak("invalid xml: $value") 0 0 0
548 0 $xml .= $value;
549 ▶ } elsif (defined $value and length $value) {
Condition33%1/3
defined $value and length $value
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $value and length $value
defined $value length $value
Truth table33%1/3
A and B
A= defined $valueB= length $value
ABresult
0X0
100
111
550 12 $xml .= "<$key>"._encode($value)."</$el_name>";
551 } else {
552 0 $xml .= "<$key/>";
553 }
554 } else {
555 9 $xml .= "<$key>@{[ _arrayref_to_xml($value, $flags) ]}</$el_name>";
556 }
557 21 ▶ if ($flags->{tidy}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags->{"tidy"}) 0 21 21
558 $xml = tidy_xml($xml, {
559 0 ▶ exists $flags->{indentstring} ? (indentstring => $flags->{indentstring}) : ()
Branch: 1 branch
BranchTrueFalseTotal
exists $flags->{'indentstring'} ? : 0 0 0
560 });
561 }
562 21 my $decl = '';
563 21 ▶ $decl .= qq'<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>\n' if $flags->{complete};
Branch: 1 branch
BranchTrueFalseTotal
if $flags->{"complete"} 0 21 21
564 21 ▶ $decl .= qq'<?xml-stylesheet type="text/xsl" href="$flags->{xslt}"?>\n' if $flags->{xslt};
Branch: 1 branch
BranchTrueFalseTotal
if $flags->{"xslt"} 0 21 21
565 21 $xml = $decl . $xml;
566  
567 21 ▶ if (defined $flags->{save}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $flags->{"save"}) 1 20 21
568 1 ▶ open my $fh, '>', $flags->{save} or croak "Error: Couldn't open file '$flags->{save}' for writing: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $flags->{"save"} or croak(qq[Error: Couldn't open file '$flags->{"save"}' for writing: $!]) 1 0 1
569 1 binmode $fh, ':encoding(UTF-8)';
570 1 print $fh $xml;
571 1 close $fh;
572 }
573  
574 21 ▶ $xml = encode_utf8($xml) if $flags->{bytes};
Branch: 1 branch
BranchTrueFalseTotal
if $flags->{"bytes"} 1 20 21
575 21 return $xml;
576 }
577  
578 127 ▶sub _flatten {
Subroutine _flatten: called CC=4 SCAR=14.0
579 127 my ($thing) = @_;
580  
581 127 ▶ if (!ref $thing) { return $thing; }
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $thing) { } 90 37 127
elsif (ref $thing eq 'HASH') { } 13 24 37
elsif (ref $thing eq 'ARRAY') { } 24 0 24
582 13 elsif (ref $thing eq 'HASH') { return map _flatten($_), %$thing; }
583 24 elsif (ref $thing eq 'ARRAY') { return map _flatten($_), @$thing; }
584 0 else { croak 'Error: reference of invalid type in simple_to_xml: '.(ref $thing); }
585 }
586  
587 37 ▶sub _key_to_string {
Subroutine _key_to_string: called CC=2 SCAR=6.9
588 37 my ($key) = @_;
589  
590 37 ▶ if (! ref $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $key) { } 19 18 37
591 19 return $key;
592 } else {
593 18 my ($tag, %attrs) = _flatten($key);
594 18 return $tag . join('', map " $_=\""._encode($attrs{$_}).'"', grep {defined $attrs{$_}} keys %attrs);
595 }
596 }
597  
598 11 ▶sub _arrayref_to_xml {
Subroutine _arrayref_to_xml: called CC=10 SCAR=24.9
599 11 my $arref = shift;
600 11 ▶ my $flags = shift || {};
Condition50%1/2
shift() || {}
l!l
110
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
601  
602 11 my $xml = '';
603  
604 11 ▶ if (ref $arref eq 'HASH') { return _hashref_to_xml($arref, $flags); }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $arref eq "HASH") 4 7 11
605  
606 7 ▶ foreach (my $i = 0; $i <= $#$arref; ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $arref->$#*) 16 7 23
607 16 my $key = $arref->[$i++];
608 16 $key = _key_to_string($key);
609 16 my ($el_name) = $key =~ /^(\S+)/;
610 16 ▶ defined $el_name or croak encode_utf8 "Error: Strange key: $key";
Branch: 1 branch
BranchTrueFalseTotal
defined $el_name or croak(&encode_utf8("Error: Strange key: $key")) 16 0 16
611 16 my $value = $arref->[$i++];
612  
613 16 ▶ if ($key eq '!as_is') {
Branch: 2 branches
BranchTrueFalseTotal
if ($key eq '!as_is') { } 0 16 16
elsif (not ref $value) { } 14 2 16
614 0 ▶ check_xml $value or croak "invalid xml: $value";
Branch: 1 branch
BranchTrueFalseTotal
$value->check_xml or croak("invalid xml: $value") 0 0 0
615 0 $xml .= $value;
616 } elsif (! ref $value) {
617 14 ▶ if (defined $value and length $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value and length $value) { } 14 0 14
Condition33%1/3
defined $value and length $value
!ll&&!rl&&r
0014
MC/DC0%0/2
defined $value and length $value
defined $value length $value
Truth table33%1/3
A and B
A= defined $valueB= length $value
ABresult
0X0
100
111
618 14 $xml .= "<$key>@{[ _encode($value) ]}</$el_name>";
619 } else {
620 0 $xml .= "<$key/>";
621 }
622 } else {
623 2 $xml .= "<$key>@{[ _arrayref_to_xml($value, $flags) ]}</$el_name>";
624 }
625 }
626 7 return $xml;
627 }
628  
629 4 ▶sub _hashref_to_xml {
Subroutine _hashref_to_xml: called CC=9 SCAR=24.2
630 4 my $hashref = shift;
631 4 ▶ my $flags = shift || {};
Condition50%1/2
shift() || {}
l!l
40
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
632  
633 4 my $xml = '';
634  
635 4 ▶ while (my ($key, $value) = each %$hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$hashref) 4 4 8
636 4 my ($el_name) = $key =~ /^(\S+)/;
637 4 ▶ defined $el_name or croak encode_utf8 "Error: Strange key: $key";
Branch: 1 branch
BranchTrueFalseTotal
defined $el_name or croak(&encode_utf8("Error: Strange key: $key")) 4 0 4
638  
639 4 ▶ if ($key eq '!as_is') {
Branch: 2 branches
BranchTrueFalseTotal
if ($key eq '!as_is') { } 0 4 4
elsif (not ref $value) { } 4 0 4
640 0 ▶ check_xml $value or croak "invalid xml: $value";
Branch: 1 branch
BranchTrueFalseTotal
$value->check_xml or croak("invalid xml: $value") 0 0 0
641 0 $xml .= $value;
642 } elsif (! ref $value) {
643 4 ▶ if (defined $value and length $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value and length $value) { } 2 2 4
Condition100%3/3
defined $value and length $value
!ll&&!rl&&r
112
MC/DC100%2/2
defined $value and length $value
defined $value length $value
Truth table100%3/3
A and B
A= defined $valueB= length $value
ABresult
0X0
100
111
644 2 $xml .= "<$key>@{[ _encode($value) ]}</$el_name>";
645 } else {
646 2 $xml .= "<$key/>";
647 }
648 } else {
649 0 $xml .= "<$key>@{[ _arrayref_to_xml($value, $flags) ]}</$el_name>";
650 }
651 }
652 4 return $xml;
653 }
654  
655  
656 =head2 xml_to_simple($raw_xml)
657  
658 Produces a very simple hash object from the raw XML string provided. An example hash object created thusly is this:
659 S<C<< { thing => { name => 'John', location => { city => 'New York', country => 'U.S.A.' } } } >>>
660  
661 B<WARNING:> This function only works on very simple XML strings, i.e. children of an element may not consist of both
662 text and elements (child elements will be discarded in that case). Also attributes in tags are ignored.
663  
664 Since the object created is a hashref (unless used with the C<arrayref> optional flag), duplicate keys will be
665 discarded.
666  
667 All strings contained in the output simple structure will always contain characters rather than octets/bytes,
668 regardless of the C<bytes> optional flag.
669  
670 Optional flags: C<internal>, C<strip>, C<file>, C<strip_ns>, C<arrayref>, C<bytes>
671  
672 =cut
673  
674 7 ▶sub xml_to_simple {
Subroutine xml_to_simple: called CC=3 SCAR=11.0
Pod documented
675 7 my $xml = shift;
676 7 ▶ my $flags = shift || {};
Condition100%2/2
shift() || {}
l!l
43
MC/DC100%1/1
shift() || {}
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
677  
678 7 my $object = xml_to_object($xml, $flags);
679  
680 7 ▶ $object = $object->simplify($flags) if defined $object;
Branch: 1 branch
BranchTrueFalseTotal
if defined $object 7 0 7
681  
682 7 return $object;
683 }
684  
685 57 ▶sub _objectarray_to_simple {
Subroutine _objectarray_to_simple: called CC=4 SCAR=14.9
686 57 my $object = shift;
687 57 ▶ my $flags = shift || {};
Condition50%1/2
shift() || {}
l!l
570
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
688  
689 57 ▶ defined $object or return undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $object or return undef 57 0 57
690  
691 return $flags->{arrayref}
692 57 ▶ ? _objectarray_to_simple_arrayref($object, $flags)
Branch: 1 branch
BranchTrueFalseTotal
$flags->{'arrayref'} ? : 0 57 57
693 : _objectarray_to_simple_hashref($object, $flags);
694 }
695  
696 57 ▶sub _objectarray_to_simple_hashref {
Subroutine _objectarray_to_simple_hashref: called CC=10 SCAR=23.6
697 57 my $object = shift;
698 57 ▶ my $flags = shift || {};
Condition50%1/2
shift() || {}
l!l
570
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
699  
700 57 ▶ defined $object or return undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $object or return undef 57 0 57
701  
702 57 my $hashref = {};
703  
704 57 foreach my $stuff (@$object) {
705 102 ▶ if (defined(my $key = $stuff->{el_name})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined(my $key = $stuff->{'el_name'})) { } 44 58 102
elsif (defined(my $value = $stuff->{'text'})) { } 58 0 58
706 44 ▶ $key = strip_ns $key if $flags->{strip_ns};
Branch: 1 branch
BranchTrueFalseTotal
if $flags->{"strip_ns"} 1 43 44
707 44 $hashref->{ $key } = _objectarray_to_simple($stuff->{content}, $flags);
708 }
709 elsif (defined(my $value = $stuff->{text})) {
710 58 ▶ $value = trim $value if $flags->{strip};
Branch: 1 branch
BranchTrueFalseTotal
if $flags->{"strip"} 0 58 58
711 58 ▶ return $value if $value =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /\S/ 25 33 58
712 }
713 }
714  
715 32 ▶ return %$hashref ? $hashref : undef;
Branch: 1 branch
BranchTrueFalseTotal
%$hashref ? : 32 0 32
716 }
717  
718 0 ▶sub _objectarray_to_simple_arrayref {
Subroutine _objectarray_to_simple_arrayref: not called CC=10 SCAR=47.0
719 0 my $object = shift;
720 0 ▶ my $flags = shift || {};
Condition0%0/2
shift() || {}
l!l
00
MC/DC0%0/1
shift() || {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
721  
722 0 ▶ defined $object or return undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $object or return undef 0 0 0
723  
724 0 my $arrayref = [];
725  
726 0 foreach my $stuff (@$object) {
727 0 ▶ if (defined(my $key = $stuff->{el_name})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined(my $key = $stuff->{'el_name'})) { } 0 0 0
elsif (defined(my $value = $stuff->{'text'})) { } 0 0 0
728 0 ▶ $key = strip_ns $key if $flags->{strip_ns};
Branch: 1 branch
BranchTrueFalseTotal
if $flags->{"strip_ns"} 0 0 0
729 0 push @$arrayref, ( $key, _objectarray_to_simple($stuff->{content}, $flags) );
730 } elsif (defined(my $value = $stuff->{text})) {
731 0 ▶ $value = trim $value if $flags->{strip};
Branch: 1 branch
BranchTrueFalseTotal
if $flags->{"strip"} 0 0 0
732 0 ▶ return $value if $value =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /\S/ 0 0 0
733 }
734 }
735  
736 0 ▶ return @$arrayref ? $arrayref : undef;
Branch: 1 branch
BranchTrueFalseTotal
@$arrayref ? : 0 0 0
737 }
738  
739  
740 =head2 check_xml($raw_xml)
741  
742 Returns true if the $raw_xml string is valid XML (valid enough to be used by this module), and false otherwise.
743  
744 Optional flags: C<file>, C<bytes>
745  
746 =cut
747  
748 2 ▶sub check_xml {
Subroutine check_xml: called CC=2 SCAR=7.0
Pod documented
749 2 my $xml = shift;
750 2 ▶ my $flags = shift || {};
Condition50%1/2
shift() || {}
l!l
02
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
751  
752 2 my $ok = eval { xml_to_object($xml, $flags); 1 };
753 2 return !!$ok;
754 }
755  
756  
757 5 1; # End of XML::MyXML
758  
759 __END__
↑ Summary MyXML/Object.pm »