Search code examples
xmlvbavbscriptapostrophe

Checking a node with an apostrophe in the value


I have a set of code that searches for a person of a particular height that the user selects in a combo box, after which removes all the subjects that don't match in a list. The values for the combo box are like this: 5'0-5'5. My problem is the apostrophes in the 5'0-5'5 are throwing up errors. Here is my code

If ComboBox5.Value <> "" Then
    i = 0  

    Do While i <= ListBox26.ListCount - 1
        Set CheckHeight = objDom.SelectSingleNode("//IDNum/LastName[@LName = '" _
            & LastName.Text & "']/FirstName[@FName='" & FirstName.Text _
            & "']/DateOfBirth[@DOB='" & Dob.Text & "']/Height[.='" _
            & ComboBox5.Value & "']")

        If CheckHeight Is Nothing Then
            ListBox26.RemoveItem (i)
        Else
            i = i + 1
        End If
    Loop

The XML looks like this:

<LastName LName="Rodriguez Jesus Luis">
  <FirstName FName="Armondo">
    <DateOfBirth DOB="7/10/1975">
       <Hair>Black</Hair> 
       <Eyes>Brown</Eyes> 
       <Weight>150 - 175 lbs</Weight> 
       <Height>5'6 - 5'9</Height> 
    </DateOfBirth>
  </FirstName>
</LastName>

I have tried replacing one apostrophe "'" with two "''", tried Chr(39), tried &apos; but still errors.

I can get it to work if I use getElementsByTagName and write a bunch more code to compare and remove, but I was hopping to use the above code as it works with other all the other fields I am using.

The error I am getting is:

Expected token ']' found 'NUMBER'.

//IDNum/LastName[@LName = 'Rodriguez Jesus Luis']/FirstName[@FName='Armondo']/DateOfBirth[@DOB='7/10/1975']/Height[.='5'-->0<-- - 5'3']


Solution

  • Use double quotes around the string that may contain single quotes. In VBScript nested double quotes in strings are escaped by doubling them:

    Set CheckHeight = objDom.SelectSingleNode("//IDNum/LastName[@LName = '" & _
      LastName.Text & "']/FirstName[@FName='" & FirstName.Text & _
      "']/DateOfBirth[@DOB='" & Dob.Text & _
      "']/Height[.=""" & ComboBox5.Value & """]")
                   ^^                       ^^
    

    As a side note, your data format is seriously messed up. Your entire hierarchy should rather be attributes of the same node:

    <Person LastName="Rodriguez Jesus Luis"
        FirstName="Armondo"
        DateOfBirth="7/10/1975"
        Hair="Black"
        Eyes="Brown"
        Weight="150 - 175 lbs"
        Height="5'6 - 5'9"
    />