0

I have the below XML of DVDs with their titles and Ratings:

<Collection>
  <DVD>
    <Title>Wild Down Under</Title
    <Rating>3 Stars</Rating>
  </DVD>
  <DVD>
    <Title>Up</Title
    <Rating>5 Stars</Rating>
  </DVD>
</Collection>

And I have the below VBScript to iterate through and echo out the DVD titles, which works okay

Set xmlDoc = CreateObject( "Microsoft.XMLDOM" )
xmlDoc.Async = "False"
xmlDoc.Load( "dvdcoll.xml" )
strQuery = "/Collection/DVD/Title"
Set colNodes = xmlDoc.selectNodes( strQuery )
For Each objNode in colNodes
  dvdTitle = objNode.text
  WScript.Echo  dvdTitle
Next

But what I want to do is somehow add the "Rating" Node into a string as well. Any idea how I can do that? It's important that Rating and Title are in separate strings.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Similar to the next question: [xml parse with vbscript](http://stackoverflow.com/q/26144567/3439404) – JosefZ Jan 21 '15 at 11:35

1 Answers1

1

(1) Fix your .xml

(2) Use a common skeleton/structure/strategy for your VBS code dealing with XML (checks, diagnostic output)

(3) Loop over all DVD nodes and access their Title and Rating nodes - as in

Option Explicit

Dim xmlObj : Set xmlObj = CreateObject("msxml2.domdocument")
xmlObj.async = False
xmlObj.Load "..\data\28065845.xml"
If xmlObj.parseError.errorCode <> 0 Then
    WScript.Echo "Error Reading File - " & xmlObj.parseError.reason
Else
    Dim sXPath : sXPath     = "/Collection/DVD"
    Dim ndlDVD : Set ndlDVD = xmlObj.selectNodes(sXPath)
    If 0 = ndlDVD.length Then
       WScript.Echo "failed:", sXPath
    Else
       Dim ndDVD
       For Each ndDVD in ndlDVD
           Dim ndTitle  : Set ndTitle  = ndDVD.selectSingleNode("Title")
           Dim ndRating : Set ndRating = ndDVD.selectSingleNode("Rating")
           WScript.Echo "found:", ndTitle.text, ndRating.text
       Next
    End If
End If

output:

cscript 28065845.vbs
found: Wild Down Under 3 Stars
found: Up 5 Stars
Community
  • 1
  • 1
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96