Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
XPath matching for object treesby samtregar (Abbot) |
on Feb 11, 2003 at 02:49 UTC ( [id://234301]=perlmeditation: print w/replies, xml ) | Need Help?? |
Greetings monks. Lately I've been working on a class implimenting a tree data structure. Each object of the class has a list of children which may contain any number of other objects of the same class, which may themselves have children. Each node has a name which identifies the type of node, like 'page' or 'paragraph'.
Many of the most common operations performed on these objects only want to affect a sub-set of the available children. For example, a loop that wants to process all paragraphs might look like:
More complex cases involve needing to operate on a subset of children defined by two or more levels of containership. For example, to collect all the headers on all the pages:
Suddenly it occurred to me that I've seen patterns like this before, in code dealing with XML. And I've seen a good solution to the problem, XPath, which I've never really gotten a good chance to use. So, today I added a method to do XPath-style matching called match(). It only supports the simplest patterns, but I plan to improve it incrementally. For example, the first block of code can be translated to:
That's no big deal, but the fun starts translating the second one:
Once I wrote match(), I realized I had another tool I didn't even realize I could use. I now have a way to unqiuely identify a node in a tree. For example, to get the third paragraph on the fourth page: ($para) = $obj->match('/page[3]/paragraph[2]'); So not only is match() a simpler and cleaner interface to selecting nodes from the tree, it also offers an entirely novel feature: unique indentifiers for nodes inside the tree. I added an xpath() method to return this path for a given node. I've already found one area in the application where this significantly reduces code complexity and I expect to find more. -sam
Back to
Meditations
|
|