Reading XML Files in WSH - More advanced queries
(Page 3 of 6 )
Okay, admittedly I haven’t done anything too fancy yet, have I? I’ve shown you how to return a single specific value from an XML file. But chances are good that if you’re using this as a database, you’re going to need to create much more complex queries than that.
More specifically, you’re probably wondering how you can filter results. For instance, you might want to query a specific field, or element. Possibly, you only want to return track information for tracks performed by a specific artist. This is all possible, and then some.
Set colTitles = objXmlDoc.selectNodes("/playlist/trackList/track/title")
For Each objTitle In colTitles
Wscript.Echo objTitle.Text
Next
If you only want your collection to return information from a specific element, you can avoid using a wildcard character and specify a particular field instead.
The Diary Of Jane
Who You Are
Executing this bit of code will result in something similar to the example above. I’m just generating a listing of the text value for a specific field; in this case, a list of each of the track's titles.
The query returns a collection containing every element in the document that matches the document path provided—specifically, the title element of every track. Note how every instance of the title element in the sample document matches the path in our query string.
Now suppose you want to return more than one specific element?
Set colProperties = objXmlDoc.selectNodes( _
"/playlist/trackList/track/(title | creator)")
For Each objProperty In colProperties
WScript.Echo objProperty.Text
Next
This piece of code returns any element that matches either title or creator. The syntax looks a bit rough, but think of the pipe (|) character as an OR operator. The OR clause is enclosed in parenthesis.
Set colProperties = objXmlDoc.selectNodes( _
"/playlist/trackList/track/(location | title | creator)")
For Each objProperty In colProperties
WScript.Echo objProperty.Text
Next
Returning additional fields is as easy as adding them inside the parenthesis. Just remember to keep them separated by pipe characters.
Next: Further filtering results >>
More Windows Scripting Articles
More By Nilpo