XML technologies / XML / Perl & XML / DOM / XML::LibXML

(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)

Matt Sergeant’s module XML::LibXML interfaces with the GNOME project’s LibXML library. This DOM implementation spread quickly, combining the speed of older modules based on XML::Parser with complete DOM 2 support, including namespaces.

We have not discussed namespaces much. Avoiding them is still common advice: they complicate markup and code by requiring local names and namespace URIs. Nevertheless, namespaces are increasingly important, and we must eventually face them. For example, the transformation language XSLT uses them to distinguish instruction tags controlling output from elements forming the output itself.

Even familiar HTML uses namespaces. They conveniently embed specialized markup, such as equations, in ordinary pages. The language MathML does this. The next example incorporates MathML and its namespace.

Example: A document with namespaces

<?xml version="1.0" encoding="ISO-8859-1"?>
<html>
    <body xmlns:eq="http://www.w3.org/1998/Math/MathML">
        <h1>Der Hauptsatz von Molly</h1>
        <p>
            Es ist allgemein bekannt, daß Katzen ihren eigenen Willen haben. Man wird eine
            Katze nie dazu bringen, sich auf einer Geraden zu bewegen, es sei denn, sie will
            es von selbst. Zwingt man eine Katze trotzdem, sich auf einer Geraden zu bewegen,
            dann steigt die Wahrscheinlichkeit, daß sie einem ins Gesicht springt, um von der
            Geraden abzuweichen, proportional zum Quadrat der Distanz der Entfernung.</p>
        <p>
            <!-- P = 1 - 1/(x^2) -->
            <eq:math>
                <eq:mi>P</eq:mi><eq:mo>=</eq:mo><eq:mn>1</eq:mn><eq:mo>-</eq:mo>
                <eq:mfrac>
                    <eq:mn>1</eq:mn>
                    <eq:msup>
                        <eq:mi>x</eq:mi>
                        <eq:mn>2</eq:mn>
                    </eq:msup>
                </eq:mfrac>
            </eq:math>
        </p>
    </body>
</html>

Tags with the prefix eq: belong to the namespace identified by "http://www.w3.org/1998/Math/MathML", declared in an attribute of the element <body>. The browser distinguishes ordinary HTML from MathML, sending qualified elements to its equation formatter rather than its HTML formatter.

Some browsers, however, are confused by MathML tags and behave unpredictably. A small tool detecting and removing namespace-qualified elements, leaving markup suitable for older HTML processors, is useful. This DOM 2 example traverses the entire document and removes every element with a namespace prefix.

First read the file:

use XML::LibXML;

my $parser = XML::LibXML->new( );
my $doc = $parser->parse_file( shift @ARGV );

Find the root and pass it to a recursive function removing qualified elements, then print the document:

my $mathuri = 'http://www.w3.org/1998/Math/MathML';
my $root = $doc->getDocumentElement;
&purge_nselems( $root );
print "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n",
      $doc->toString;

This function takes an element node. If it has a namespace prefix, remove it from its parent’s children; otherwise recurse through its child elements.

sub purge_nselems {    
   my $elem = shift;
   return unless( ref( $elem ) =~ /Element/ );
   if( $elem->prefix ) {
      my $parent = $elem->parentNode;
      $parent->removeChild( $elem );
   } elsif( $elem->hasChildNodes ) {
      my @children = $elem->getChildnodes;
      foreach my $child ( @children ) {
     &purge_nselems( $child );
    }
  }
}

This implementation adds Perl conveniences absent from the official DOM interface. For example, the method getChildnodes returns a normal Perl list in array context rather than a cumbersome object NodeList. In scalar context it returns the number of children, so objects NodeList are never used.

Such simplifications are normal in Perl: ease of use generally outweighs formal rigor. Hopefully future Perl DOM implementations follow the same conventions. These issues are discussed extensively on the mailing list perl-xml, currently considering how to integrate SAX2 and namespaces logically while retaining Perl idioms.

Matt Sergeant added other treats to XML::LibXML. The class Node has a method findnodes( ) that takes and evaluates an expression in XPath, making node searches easier than ordinary DOM. Parser options control strictness, whether and how to resolve entities, and whitespace significance. Special handlers can also manage unresolved entities. Overall, it is excellent for DOM programming.

  

  

 

 

 

back to top