#!/usr/bin/perl -w use strict; use warnings; use Getopt::Long; use XML::LibXML; use Net::LDAP::LDIF; my $HELP = <] [-e ] [-n []] [-s] [-h] -d Use instead of "ldif2xml" as document element -e Use instead of "entry" to enclose each entry -n [] Output the dn of each entry; if provided, use as element name instead of "dn"; by default, the dn is omitted from the output -s Strip leading and trailing whitespace from each value -h Print this help ;-) EOH sub createTextElement ($$$$$) { my ($xml, $parent, $attribute, $value, $strip) = @_; if ($strip) { $value =~ s/^\s+//; $value =~ s/\s+$//; } my $attrElem = $xml->createElement($attribute); $parent->addChild($attrElem); my $textNode = $xml->createTextNode($value); $attrElem->addChild($textNode); } my ($docName, $entryName) = ("ldif2xml", "entry"); my ($dnName, $strip); GetOptions( "d=s" => \$docName, "e=s" => \$entryName, "n:s" => sub { $dnName = ($_[1] ? $_[1] : "dn"); }, "s" => \$strip, "h" => sub { print $HELP; exit; }, ) || exit(1); my $xml = XML::LibXML->createDocument("1.0", "UTF-8") || die "Cannot create XML document"; my $docElem = $xml->createElement($docName); $xml->setDocumentElement($docElem); my $ldif = Net::LDAP::LDIF->new(\*STDIN, onerror => "die") || die "Cannot read LDIF data from STDIN"; while (!$ldif->eof()) { my $entry = $ldif->read_entry() || die "Cannot read LDIF entry from STDIN"; if ($ldif->error()) { die $ldif->error(), "\n", $ldif->error_lines(), "\n"; } my $entryElem = $xml->createElement($entryName); $docElem->addChild($entryElem); if ($dnName) { createTextElement($xml, $entryElem, $dnName, $entry->dn(), $strip); } foreach my $attr($entry->attributes()) { foreach my $value($entry->get_value($attr)) { createTextElement($xml, $entryElem, $attr, $value, $strip); } } } print $xml->toString(1);