JavaScript / Rhino: can I use a regular expression in an E4X query to select specific nodes?
I am working on Rhino (Mirth) and I need to process / parse XML with the following structure:
<root>
<row>
<foo-1 />
<foo-2 />
<foo-3 />
<foo-4 />
...
<bar-1 />
<bar-2 />
<bar-3 />
<bar-4 />
...
<something-else-1 />
<something-else-2 />
</row>
</root>
I only want to get all the "foo" nodes, while avoiding using loops. I tried to sleep like:
xml.row.(new RegExp("foo[1-4]").test()))
and multiple variations of the same line, but it doesn't seem to work. Is there any E4X syntax / method to do this? I've been searching the internet for a while and I've read the ECMAS documentation, but I can't seem to do it.
Thanks in advance!
This is how you should be able to do it, but it doesn't work in Rhino:
xml.row.*.( /foo-[1-4]/.test(name()) ) // or localName()
For now, as far as I know, you will need to use a loop.
If you don't mind getting an array instead of XMLList , and your version of Rhino supports array methods, you can use this:
[foo for each (foo in xml.row.*) if (/foo-[1-4]/.test(foo.name()))]
It still uses a loop, but it is at least a little declarative.
Edit: As Elijah Gray mentioned in the comments, if you are using namespaces you need to either call localName()
or name().localName
. Of course, to be completely correct, you will also need to compare the namespace URIs.
Also, obviously SpiderMonkey (Firefox) requires function calls to be prefixed with function::
in filter predicates, so the filter would look like this:
/foo-[1-4]/.test(function::name()) // or function::localName()
Typically, Rhino follows what SpiderMonkey does, so when it supports function calls in predicates, you may need a prefix function::
.
source to share
A bug against Rhino related to this behavior. If you are feeling brave, you can try the patch suggested by Martin Blom as noted in the bug comments.
source to share