| XML::Hash::XS(3pm) | User Contributed Perl Documentation | XML::Hash::XS(3pm) | 
XML::Hash::XS - Simple and fast hash to XML and XML to hash conversion written in C
    use XML::Hash::XS;
    my $xmlstr = hash2xml \%hash;
    hash2xml \%hash, output => $fh;
    my $hash = xml2hash $xmlstr;
    my $hash = xml2hash \$xmlstr;
    my $hash = xml2hash 'test.xml', encoding => 'cp1251';
    my $hash = xml2hash $fh;
    my $hash = xml2hash *STDIN;
Or OOP way:
    use XML::Hash::XS qw();
    my $conv   = XML::Hash::XS->new(utf8 => 0, encoding => 'utf-8')
    my $xmlstr = $conv->hash2xml(\%hash, utf8 => 1);
    my $hash   = $conv->xml2hash($xmlstr, encoding => 'cp1251');
This module implements simple hash to XML and XML to hash conversion written in C.
During conversion uses minimum of memory, XML or hash is written directly without building DOM.
Some features are optional and are available with appropriate libraries:
$hash is reference to hash
    hash2xml
        {
            node1 => 'value1',
            node2 => [ 'value21', { node22 => 'value22' } ],
            node3 => \'value3',
            node4 => sub { return 'value4' },
            node5 => sub { return { node51 => 'value51' } },
        },
        canonical => 1,
        indent    => 2,
    ;
will convert to:
    <?xml version="1.0" encoding="utf-8"?>
    <root>
      <node1>value1</node1>
      <node2>value21</node2>
      <node2>
        <node22>value22</node22>
      </node2>
      <node3>value3</node3>
      <node4>value4</node4>
      <node5>
        <node51>value51</node51>
      </node5>
    </root>
and (use_attr=1):
    hash2xml
        {
            node1 => 'value1',
            node2 => [ 'value21', { node22 => 'value22' } ],
            node3 => \'value3',
            node4 => sub { return 'value4' },
            node5 => sub { return { node51 => 'value51' } },
        },
        use_attr  => 1,
        canonical => 1,
        indent    => 2,
    ;
will convert to:
    <?xml version="1.0" encoding="utf-8"?>
    <root node1="value1" node3="value3" node4="value4">
      <node2>value21</node2>
      <node2 node22="value22"/>
      <node5 node51="value51"/>
    </root>
$xml may be string, reference to string, file handle or tied file handle:
    xml2hash '<root>text</root>';
    # output: 'text'
    xml2hash '<root a="1" b="2">text</root>';
    # output: { a => '1', b => '2', content => 'text' }
    open(my $fh, '<', 'test.xml');
    xml2hash $fh;
    xml2hash *STDIN;
if indent is "0", XML output will all be on one line.
if output is undefined, XML document dumped into string.
if output is FH, XML document writes directly to a filehandle or a stream.
if canonical is "0", order of the element will be pseudo-randomly.
if use_attr is "0", converter will be use tags only.
if xml_decl is "0", XML declaration will not be output.
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.
Sample:
    xml2hash($xml, filter => qr[/root/item\d$], cb => sub {
        print $_[0], "\n";
    });
    # 111
    # 222
    # 333
    
  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
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>
    
  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>
    
  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:
    my $sth = $dbh->prepare('SELECT * FROM foo WHERE bar=?');
    $sth->execute(...);
    my $o = bless {}, 'Iterator';
    *Iterator::iternext = sub { $sth->fetchrow_hashref() };
    open(my $fh, '>', 'data.xml');
    hash2xml({ row => $o }, use_attr => 1, indent => 2, xml_decl => 0, output => $fh);
    =>
    <root>
      <row bar="..." ... />
      <row bar="..." ... />
      ...
    </root>
    
  Performance benchmark in comparison with some popular modules(hash2xml):
                    Rate     XML::Hash XML::Hash::LX   XML::Simple XML::Hash::XS
    XML::Hash     65.0/s            --           -6%          -37%          -99%
    XML::Hash::LX 68.8/s            6%            --          -33%          -99%
    XML::Simple    103/s           58%           49%            --          -98%
    XML::Hash::XS 4879/s         7404%         6988%         4658%            --
Benchmark was done on <http://search.cpan.org/uploads.rdf>
Yuriy Ustushenko, <yoreek@yahoo.com>
Copyright (C) 2012-2021 Yuriy Ustushenko
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| 2022-10-20 | perl v5.36.0 |