Subject: | Provide a method to determine if an element has an explicit ID |
I am processing XML for a glossary, where some elements have IDs and some do not:
====
<glossary>
<entry>
<term>apple</term>
<definition>a red fruit</definition>
</entry>
<entry id="HFECDBAC>
<term>banana</term>
<definition>a yellow fruit</definition>
</entry>
<entry>
<term>orange</term>
<definition>an orange fruit</definition>
</entry>
</glossary
====
I want to set IDs only on <term> elements that don't already have an existing ID. The problem is that sometimes $term->id is undefined and sometimes it is set to twig_id_* (due to processing in the area, I assume). To handle both cases, I need to do
====
foreach my $entry ($g->descendants('entry')) {
$entry->set_id(simple_name($entry->first_child('term')->text)) if (!defined($entry->id) or $entry->id =~ m!^twig_id_!);
}
====
It would be nice to collapse the two tests (undefined OR a twig ID) into a "has_id" method:
====
foreach my $entry ($g->descendants('entry')) {
$entry->set_id(simple_name($entry->first_child('term')->text)) if !($entry->has_id);
}
====
(Note: I prefer the ID existence approach to a "set_id_if_undefined" approach because the computation of the potential ID could be expensive, and should be computed only when needed.)