Ejemplos de uso de SAX

Ejemplo 1 (Python)

import xml.parsers.expat
 
# Elemento que abre
def start_element(name, attrs):
    print '(Elemento abre:', name, attrs
 
# Elemento que cierra
def end_element(name):
    print ')Elemento cierra:', name
 
# Contenido entre tags
def char_data(data):
    print '-Contenido:', repr(data)
 
p = xml.parsers.expat.ParserCreate()
 
p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data
 
arch = open("prueba.xml")
p.Parse(arch.read(), 1)
arch.close()

Ejemplo 2 (Perl)

#!/usr/bin/perl
use strict;
use XML::Parser;
 
sub traverse
{
    my $node = shift;
    while ( defined ( my $element = shift @{ $node } )) {
        my $child = shift @{ $node };
        if ( ref $child ) # if $child is yet another arrayref node
        {
            my %attr = %{ shift @{ $child } };
                # yank the attributes out of the grandchild
            print "$element has attributes @{[ %attr ]}\n";
            traverse( $child );
                # child element is now just a list of element/children pairs
        }
        else # otherwise, if $child is just some text
        {
            print "$child\n";
        }
    }
}
 
my $p = XML::Parser->new
(
    Style => "Tree",
);
my $input = "life.xml";
traverse( $p->parsefile( $input ) );
#print  $p->parsefile( $input );
exit(0);

Ejemplo 3 (Scheme)

(require (lib "xml.ss" "xml"))
 
(define arch (open-input-file "prueba.xml"))
 
 
(define xdoc (read-xml arch))
 
(close-input-port arch)
 
(define res (xml->xexpr (document-element xdoc)))
 
(display-xml xdoc)
 
(newline)
(for-each (lambda (x) (display x) ) res)
 
(display (xexpr->string res))
 
materias/laboratorio_de_lenguajes_ii/lableng2/ejemplossax.txt · Última modificación: 2011/01/24 15:30 (editor externo)
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki