I enjoy using libraries that have built query support for XML. Much of the data that is generated by my organization’s internal applications is in the form of XML. 9 times out of 10 I have to parse that data for values to be used for my development. My most recent development project prompted me to use Dojo for my development.
The XML that I had to parse required querying for node with text of a certain value. The native :contains pseudo shipped with dojo didn’t work because it uses the innerHTML property which isn’t available for XML nodes. I could have rewritten that pseudo but that would potentially break other code. I decided to create my own pseudo with the logic used in jQuery’s :contains pseudo:
1 2 3 4 5 6 7 8 9 | dojo.query.pseudos.text = function(name, condition){ var cz = condition.charAt(0); if( cz == '"' || cz == "'" ){ //remove quote condition = condition.slice(1, -1); } return function(elem){ return ((elem.textContent || elem.innerText || "").indexOf(condition) >= 0); } }; |
Using the following XML:
<?xml version="1.0"?> <catalog> <book id="bk101"> <author>Grisham, John</author> <title>The Confession: A Novel</title> </book> <book id="bk102"> <author>Morrison, Matthew</author> <title>One Day More</title> </book> <book id="bk103"> <author>Grisham, John</author> <title>The Partner</title> </book> <book id="bk104"> <author>Grisham, John</author> <title>Theodore Boone: Kid Lawyer</title> </book> <book id="bk105"> <author>Morrison, Matthew</author> <title>It Takes Two</title> </book> </catalog>
I could find all books by John Grisham using the following:
1 2 3 | dojo.query('book', xml).filter(function(book){ return dojo.query('author:text(Grisham, John)', book).length > 0; }); |


