package Text::Restructured::Writer::LibXML;
use strict;
use warnings;
use XML::LibXML;
$Text::Restructured::Writer::LibXML::VERSION='0.01';
sub new {
my ($class)=@_;
return bless {},$class;
}
sub ProcessDOM {
my ($self,$dudom)=@_;
my $xdoc=XML::LibXML->createDocument();
$xdoc->setDocumentElement(_docutils2xml($dudom,$xdoc));
return $xdoc;
}
my $MATHML='http://www.w3.org/1998/Math/MathML';
sub _mathml2xml {
my ($mnode,$xdoc)=@_;
if ($mnode->isText) {
return $xdoc->createTextNode($mnode->nodeValue);
}
my @children=map {_mathml2xml($_,$xdoc)}
$mnode->childNodes();
my $elem=$xdoc->createElementNS($MATHML,$mnode->nodeName);
for my $attname ($mnode->attributeList) {
next if $attname eq 'xmlns';
$elem->setAttribute($attname,
$mnode->attribute($attname))
}
$elem->appendChild($_) for @children;
return $elem;
}
sub _docutils2xml {
my ($dunode,$xdoc)=@_;
if ($dunode->{tag} eq '#PCDATA') {
return $xdoc->createTextNode($dunode->{text} || '');
}
if ($dunode->{tag} eq 'mathml') {
return _mathml2xml($dunode->{attr}{mathml},$xdoc);
}
my @children=map {_docutils2xml($_,$xdoc)}
@{ $dunode->{content} || [] };
my $elem=$xdoc->createElement($dunode->{tag});
if (defined $dunode->{attr}) {
while (my ($attname,$attval)=each %{$dunode->{attr}}) {
if (! defined $attval) {
$attval='';
}
elsif (ref($attval) eq 'ARRAY') {
$attval=join ' ',@$attval;
}
$elem->setAttribute($attname,$attval);
}
}
$elem->appendChild($_) for @children;
return $elem;
}
1;