Reading XML Files in WSH - Further filtering results
(Page 4 of 6 )
Let’s not stop there. To truly harness the power of a database, you need to be able to perform conditional queries. In WMI you would associate these with Where clauses. Where clauses serve to further filter your results based upon field values—or in this case, element text values.
Set colTracks = objXmlDoc.selectNodes( _
"/playlist/trackList/track [creator = 'Breaking Benjamin']")
For Each objTrack In colTracks
Set colProperties = objTrack.childNodes
For Each objProperty In colProperties
WScript.Echo objProperty.baseName & ":", objProperty.Text
Next
WScript.Echo ""
Next
This code sample will return all track instances where the creator value is equal to “Breaking Benjamin.” In other words, it only returns tracks recorded by Breaking Benjamin.
The important thing to see here is the use of brackets to denote the “where” clause. The query lists all elements that match the path provided (which represent individual track entries) and then further filters them based on the value of the track’s creator element—returning only those whose value is equal to the value provided.
But it doesn’t stop there. You can use any of the standard comparison operators including =, <, >, <=, and >=. You can negate any of them by prefacing them with an exclamation point. For example, to specify "not equal" you would use !=.
Set colTracks = objXmlDoc.selectNodes( _
"/playlist/trackList/track [creator != 'Breaking Benjamin']")
So this example would then return all track entries except those recorded by Breaking Benjamin. Pretty cool, huh? Okay, so you’re still not that impressed. Fine, let’s make it a little more complicated. Let’s filter our results based on more than one field.
Set colTracks = objXmlDoc.selectNodes( _
"/playlist/trackList/track " _
& "[creator = 'Breaking Benjamin' and title != 'So Cold']")
You can specify more than one element to filter by combining them into more complex query statements inside of the brackets. In this case, I’ve used the “and” operator to return all tracks where the creator element contains “Breaking Benjamin” and the title element does not contain “So Cold.” You can also create converse statements by using the “or” operator.
Next: Constructing advanced queries >>
More Windows Scripting Articles
More By Nilpo