Need to find root element name of XML file

Given this XML:

<?xml version="1.0"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
</catalog>

I'm using the following code to determine if the root element is 'catalog' or not.

#!/usr/bin/perl
use File::Basename;
use XML::LibXML;
use XML::LibXML::XPathContext;
my $inputFile = $ARGV[0];
my($XMLfile, $inputpath) = fileparse($inputFile);
chdir($inputpath) or die "Can\'t chdir to $inputpath";
 
my $doc = XML::LibXML->new()->parse_file($XMLfile);
my $xp = XML::LibXML::XPathContext->new($doc);
$object = $xp->exists('/catalog');
print $object ."\n";

This works fine for a <catalog> file, but I also need to determine other file types by reading the root element. Does anyone know of a method using XML::LibXML (or similar) module that would return the name of the root element?

Hi,

There is a method called getDocumentElement() in XML:: DOM and remember reading something similar in LibXML. Please search for a similar method.

thanks for the reply, but something a little more specific would be more helpful.

---------- Post updated 07-22-11 at 11:50 AM ---------- Previous update was 07-21-11 at 10:57 PM ----------

I found a solution for anyone searching this thread:

#!/usr/bin/perl
use File::Basename;
use XML::DOM;
my $inputFile = $ARGV[0];
my($XMLfile, $inputpath) = fileparse($inputFile);
chdir($inputpath) or die "Can\'t chdir to $inputpath";
my $parser = new XML::DOM::Parser;
my $doc = $parser->parsefile($XMLfile) or die "Could not parse!";
my $docNode   = $doc->getDocumentElement->getTagName;
print "Tag Name: ".$docNode."\n";