Search code examples
xmlvbscripthta

Search attribute value in XML file


I need to search strings in an XML file that contains a unique string

<CSVName Value="standard.csv" />

This value changes between "standard.csv" and "non-standard.csv".

I am using VBScript to search "standard.csv" or "non-standard.csv". If it matches "standard.csv" it will echo me "This is standard", if it matches "non-standard.csv" it will echo me "This is non-stanadard".

This is part of my HTA for this function when clicking a button, I dont know how to make pattern of reg exp for matching "A" or "B" then echo each accordingly.

<html>
<head>
<title></title>
<HTA:APPLICATION
  APPLICATIONNAME=""
  ID=""
  VERSION="1.0"/>
</head>

<script language="VBScript">

ub RUNCURRENTMODE
      Const ForReading = 1

      Set objRegEx = CreateObject("VBScript.RegExp")
      objRegEx.Pattern = (?:"standard.csv"|"non-standard.csv")

      Set objFSO = CreateObject("Scripting.FileSystemObject")
      Set objFile = objFSO.OpenTextFile("C:\aaa\settings.xml", ForReading)

      strSearchString = objFile.ReadAll
      objFile.Close

      If 
       .
       .
       .
      End If
    End Sub

</script>

<body bgcolor="buttonface">
<center>
<p><font face="verdana" color="red">CSV MODE SWITCH</font></p>
YOU ARE CURRENTLY IN STANDARD CSV MODE <p>
<input id=runbutton  class="button" type="button" value="CURRENT MODE" name="db_button"  onClick="RUCURRENTMODE" style="width: 170px"><p>
</center>


</body>
</html>

Solution

  • To answer the immediate question, the Pattern property expects a string, so you'd have to change this:

    objRegEx.Pattern = (?:"standard.csv"|"non-standard.csv")
    

    into this:

    objRegEx.Pattern = "(?:standard\.csv|non-standard\.csv)"
    

    You could even simplify the expression to this:

    objRegEx.Pattern = "(?:non-)?standard\.csv"
    

    However, apparently you have an XML file there, so you shouldn't be using regular expressions for this in the first place. Use an actual XML parser to extract the information:

    Set xml = CreateObject("Msxml2.DOMDocument.6.0")
    xml.async = False
    xml.load "C:\aaa\settings.xml"
    
    If xml.ParseError Then
      MsgBox xml.ParseError.Reason
      self.Close()  'or perhaps "Exit Sub"
    End If
    
    For Each n In xml.SelectNodes("//CSVName")
      Select Case n.Attributes.GetNamedItem("Value").Text
        Case "standard.csv"     : MsgBox "This is standard."
        Case "non-standard.csv" : MsgBox "This is non-standard."
        Case Else               : MsgBox "Unexpected value."
      End Select
    Next