How to create a new XML::DOM::Document root in perl



I'm trying to modify some code that was using LibXML to use XML::DOM instead as LibXML isn't available on my fatcow server. My question is: How can I set the root document of a XML::DOM::Document? There is no setDocumentElement method in XML::DOM::Document.


Here is the code in question (from XML2JSON.pm), with the line I'm trying to figure out how to replace marked with **********:



=head2 obj2dom

Takes a perl data structure as input. (Must be a hashref.)
Returns an XML::DOM::Document object. #JMO

This method expects the object to be in the same format as
would be returned by the xml2obj method.

=cut

sub obj2dom
{
my ( $Self, $Obj ) = @_;

croak "Object must be a hashref" unless ref($Obj) eq 'HASH';

my $Version = $Obj->{ $Self->{attribute_prefix} . 'version' } || $Obj->{'version'} || '1.0';
my $Encoding = $Obj->{ $Self->{attribute_prefix} . 'encoding' } || $Obj->{'encoding'} || 'UTF-8';

#my $Dom = $XMLPARSER->createDocument( $Version, $Encoding ); #JMO
my $Dom = XML::DOM::Document->new(); #JMO
$Dom->setXMLDecl($Dom->createXMLDecl($Version, $Encoding)); #JMO

my $GotRoot = 0;

#delete @$Obj{ grep { /^$Self->{attribute_prefix}/ } keys %$Obj };

foreach my $Key ( keys %$Obj )
{
$Obj->{$Key} = "" unless defined($Obj->{$Key});

my $RefType = ref( $Obj->{$Key} );
warn "Value ref type for $Key is: $RefType (value seems to be $Obj->{$Key})" if $Self->{debug};

my $Name = $Key;

# replace a "$" in the name with a ":"
$Name =~ s/([^^])\$/$1\:/;

if ( $RefType eq 'HASH' )
{
warn "Creating root element: $Name" if $Self->{debug};

croak "You may only have one root element: $Key" if $GotRoot;
$GotRoot = 1;

my $Root = $Dom->createElement($Name);
$Dom->setDocumentElement($Root); # **********

$Self->_process_element_hash( $Dom, $Root, $Obj->{$Key} );
}
elsif ( $RefType eq 'ARRAY' )
{
croak "You cant have an array of root nodes: $Key";
}
elsif ( !$RefType )
{
if ( $Obj->{$Key} ne '' )
{
unless ($GotRoot)
{
my $Root;
eval { $Root = $Dom->createElement($Name) };
if ( $@ ) {
die "Problem creating root element $Name: $@";
}
$Dom->setDocumentElement($Root); # **********
$Root->appendText( $Obj->{$Key} );
$GotRoot = 1;
}
}
else
{
croak "Invalid data for key: $Key";
}
}
else
{
warn "unknown reference: $RefType";
}
}

return $Dom;
}


Thanks in advance for your help!!


No comments:

Post a Comment