XML-Hash-XS
view release on metacpan or search on metacpan
C-undef-%23-in+out-handy>.
utf8 [ = 1 ] *# hash2xml+xml2hash*
Turn on utf8 flag for strings if enabled.
max_depth [ = 1024 ] *# xml2hash*
Maximum recursion depth.
buf_size [ = 4096 ] *# hash2xml+xml2hash*
Buffer size for reading end encoding data.
keep_root [ = 1 ] *# hash2xml+xml2hash*
Keep root element.
filter [ = undef ] *# xml2hash*
Filter nodes matched by pattern and return reference to array of
nodes.
Sample:
my $xml = <<'XML';
<root>
<item1>111</item1>
<item2>222</item2>
<item3>333</item3>
</root>
XML
my $nodes = xml2hash($xml, filter => '/root/item1');
# $nodes = [ 111 ]
my $nodes = xml2hash($xml, filter => ['/root/item1', '/root/item2']);
# $nodes = [ 111, 222 ]
my $nodes = xml2hash($xml, filter => qr[/root/item\d$]);
# $nodes = [ 111, 222, 333 ]
It may be used to parse large XML because does not require a lot of
memory.
cb [ = undef ] *# xml2hash*
This option is used in conjunction with "filter" option and defines
callback that will called for each matched node.
Sample:
xml2hash($xml, filter => qr[/root/item\d$], cb => sub {
print $_[0], "\n";
});
# 111
# 222
# 333
method [ = 'NATIVE' ] *# hash2xml*
experimental support the conversion methods other libraries
if method is 'LX' then conversion result is the same as using
XML::Hash::LX library
Note: for 'LX' method following additional options are available:
attr cdata text comm
OBJECT SERIALISATION(hash2xml)
1. When object has a "toString" method
In this case, the <toString> method of object is invoked in scalar
context. It must return a single scalar that can be directly encoded
into XML.
Example:
use XML::LibXML;
local $XML::LibXML::skipXMLDeclaration = 1;
my $doc = XML::LibXML->new->parse_string('<foo bar="1"/>');
print hash2xml({ doc => $doc }, indent => 2, xml_decl => 0);
=>
<root>
<doc><foo bar="1"/></doc>
</root>
2. When object has overloaded stringification
In this case, the stringification method of object is invoked and
result is directly encoded into XML.
Example:
package Test {
use overload '""' => sub { shift->stringify }, fallback => 1;
sub new {
my ($class, $str) = @_;
bless { str => $str }, $class;
}
sub stringify {
shift->{str}
}
}
my $obj = Test->new('test string');
print hash2xml({ obj => $obj }, indent => 2, xml_decl => 0);
=>
<root>
<obj>test string</obj>
</root>
3. When object has a "iternext" method ("NATIVE" method only)
In this case, the <iternext> method method will invoke a few times
until the return value is not undefined.
Example:
my $count = 0;
my $o = bless {}, 'Iterator';
*Iterator::iternext = sub { $count++ < 3 ? { count => $count } : undef };
print hash2xml({ item => $o }, use_attr => 1, indent => 2, xml_decl => 0);
=>
<root>
<item count="1"/>
<item count="2"/>
<item count="3"/>
</root>
This can be used to generate a large XML using minimum memory, example
with DBI:
( run in 1.104 second using v1.01-cache-2.11-cpan-39bf76dae61 )