Commits

Toby Inkster committed 7781d58

overloading array deref and hash deref for XML::LibXML::Element

Comments (0)

Files changed (3)

 use XML::LibXML qw(:ns :libxml);
 use Carp;
 
+use overload
+    '%{}'  => 'getAttributesHash',
+    '@{}'  => 'childNodes',
+    'bool' => sub { 1 },
+    ;
+
+sub getAttributesHash {
+    my $self = shift;
+    my %attr;
+    foreach ($self->attributes) {
+        next if $_->isa('XML::LibXML::Namespace');
+        my $ns  = $_->namespaceURI;
+        my $key = $_->localname;
+        $attr{defined $ns ? "{$ns}$key" : $key} = $_->value;
+    }
+    \%attr
+}
+
 sub setNamespace {
     my $self = shift;
     my $n = $self->nodeName;
 
         </variablelist>
 	</sect1>
+	<sect1>
+	  <title>Overloading</title>
+	  <para>XML::LibXML::Element overloads hash dereferencing to
+	  provide access to the element's attributes. For non-namespaced
+	  attributes, the attribute name is the hash key, and the attribute
+	  value is the hash value. For namespaced attributes, the hash key
+	  is qualified with the namespace URI, using Clark notation.</para>
+	  <para>XML::LibXML::Element overloads array dereferencing to
+	  provide access to the element's contents - all child text nodes
+	  and elements are included (including text nodes consisting
+	  entirely of whitespace).</para>
+	</sect1>
     </chapter>
 
     <chapter id="XML-LibXML-Text">
+use strict;
+use warnings;
+use Test::More tests => 6;
+use XML::LibXML;
+
+my $root = XML::LibXML->load_xml( IO => \*DATA )->documentElement;
+
+isa_ok
+	$root->[0],
+	'XML::LibXML::Text',
+	'text nodes in array deref';
+
+isa_ok
+	$root->[1],
+	'XML::LibXML::Element',
+	'element nodes in array deref';
+
+is
+	$root->[1]{'attr1'},
+	'foo',
+	'non-namespaced attribute';
+
+is
+	$root->[1]{'{http://localhost/}attr2'},
+	'bar',
+	'namespaced attribute';
+
+is
+	$root->[3][0]->textContent,
+	'Hello world',
+	'more deeply nested';
+
+is
+	$root->[3]{'attr1'},
+	'baz',
+	'things can overload @{} and %{} simultaneously';
+
+__DATA__
+<root>
+	<elem1 attr1="foo" xmlns:x="http://localhost/" x:attr2="bar" />
+	<elem2 attr1="baz">Hello world</elem2>
+</root>