Re: What would you like to see in XML::LibXML ?

Aaron Crane <[email protected]> Sun, 29 Jan 2012 14:49:36 +0000
Newsgroups gmane.comp.lang.perl.xml
Message-ID <CACmk_tsEmiE8wK0vhXNUuHgJwG7V5s+-ANAwEi6WSb59SHHXdg@mail.gmail.com>
Shlomi Fish <[email protected]> wrote:
> 2. Are there features in the more Perly parts that you wish to see implemented?

Sorry for the delay in responding.

I'd particularly value the ability to annotate a node with a Perl
scalar, and retrieve that scalar later — much like the per-node
`_private` data in libxml2, but accessible to Perl code.  Straw-man
API:

    for my $node ($doc->findnodes($xpath1)) {
        $node->setAnnotation(some_slow_computation_on($node));
    }

    # later...
    for my $node ($doc->findnodes($xpath2)) {
        my $annotation = $node->annotation or next;
        say $annotation->some_method;
    }

    # once we're done with the annotations...
    $_->removeAnnotation for $doc->findnodes('//node()');

Alternatively, it might perhaps be better to always use a hash for the
annotations, and require a hash key to be passed to the relevant
methods:

    for my $node ($doc->findnodes($xpath1)) {
        $node->setAnnotation(cached => some_slow_computation_on($node));
    }

    # later...
    for my $node ($doc->findnodes($xpath2)) {
        my $cached = $node->annotation('cached') or next;
        say $cached->some_method;
    }

    # annotation names for a particular node:
    my @names = $node->annotationNames;

    # once we're done with the annotations...
    for my $node ($doc->findnodes('//node()')) {
        $node->removeAnnotation($_) for $node->annotationNames;
        # Maybe there should also be $node->removeAllAnnotations()
    }

I believe the tricky bit is ensuring that the annotations always have
their reference counts updated at precisely the right time.

As far as I can tell, there are deficiencies in all the alternative
approaches that don't require additional support from XML::LibXML.
The refaddr of a Node instance isn't stable during the lifetime of a
document, so it can't be used as a key in an external data structure.
The same also appears to be true of the value obtained by
dereferencing a node instance, `$$node`.  Currently, I do something
similar using attributes, but this has several deficiencies:

- Only element nodes can be annotated
- You have to select attribute names so as not to conflict with
attributes used in the document
- Storing any annotation data other than a string requires an
additional external data structure
- If the annotated document must be passed to other code (either
in-memory, or by serializing), and that code would be confused by
additional attributes, the pseudo-annotation attributes must be
carefully removed first

-- 
Aaron Crane ** http://aaroncrane.co.uk/
_______________________________________________
Perl-XML mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs