How to convert a string to XML & Get that XML ChildNode values in Classic asp? - asp-classic

`Here I have converted one string to XML:
xmlString =
" <?xml version='1.0' encoding='UTF-8' standalone='yes'?>" & _
" <hub:notifications>" & _
" <hub:notificationId>728dc361-8b4f-4acc-ad2d-9a63125c5114</hub:notificationId>" & _
" <hub:notificationId>5b7c6989-ee27-422c-bbed-2f2c36136c5b</hub:notificationId>" & _
" <hub:notificationId>67d1fffe-ab3f-43e3-bb03-24926debe2dc</hub:notificationId>" & _
" </hub:notifications>"
objXML.LoadXml(xmlString)
set Node = objXML.selectSingleNode("hub:notifications/hub:notificationId")
i = 0
Count = 0
For Each Node In objXML.selectNodes("hub:notifications")
ReDim Preserve aryNotificationIDs (i + 1)
aryNotificationIDs(i) = Node.selectSingleNode("hub:notificationId").text
Count++
Next
Response.write Count
In above, I am not getting Count of Child nodes
and How to get the child node values.
Can any one help me?
Thanks,
Jagadi`

There are many problems with your posted code.
FirstWhat language are you using? There seems to be styles from VBScript and JScript. It is predominately VBScript so I'm going to assume that is what you meant to use throughout.
Second
The XML declaration needs to be the first characters in the string.
That is:
"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" & _
not
" <?xml version='1.0' encoding='UTF-8' standalone='yes'?>" & _
Third
XML with namespaces requires an xml namespace declaration in the top-level node that use the namespace.
For example the root node.
<hub:notifications>
would become
<hub:notifications xmlns:hub='http://stackoverflow.com'>
But you would replace the stackoverflow URL with one appropriate to you.
Fourth
If you want to iterate through the child nodes of hub:notifications then you need to change the FOR deceleration to:
For Each Node In objXML.selectSingleNode("hub:notifications").childNodes
Fifth
i is not increasing in your loop, so you are setting aryNotificationIDs(1) to the different values of the nodes.
Sixth
Related to the first. There is no ++ operator in VBScript. And you don't need both i and Count in the For loop.
Additionally
You don't need to cycle through the nodes to get a count. You can use an xpath selector, and the length property. E.g. objXML.selectNodes("hub:notifications/hub:notificationId").length
Finally
I have taken you code and applied the above suggestions, I've also included an error checking part that checks that the xml has correctly loaded. The code below will output the count of hub:notificationId nodes, and list all the values in the array aryNotificationIDs. I've removed other superfluous code.
xmlString = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" & _
" <hub:notifications xmlns:hub='http://stackoverflow.com'>" & _
" <hub:notificationId>728dc361-8b4f-4acc-ad2d-9a63125c5114</hub:notificationId>" & _
" <hub:notificationId>5b7c6989-ee27-422c-bbed-2f2c36136c5b</hub:notificationId>" & _
" <hub:notificationId>67d1fffe-ab3f-43e3-bb03-24926debe2dc</hub:notificationId>" & _
" </hub:notifications>"
Set objXML = Server.CreateObject("Msxml2.DOMDocument")
objXML.LoadXml(xmlString)
If objXML.parseError.errorCode <> 0 Then
Response.Write "<p>Parse Error Reason: " & objXML.parseError.reason & "</p>"
Else
For Each node In objXML.selectSingleNode("hub:notifications").childNodes
ReDim Preserve aryNotificationIDs(i)
aryNotificationIDs(i) = node.text
i = i + 1
Next
Response.Write "<p>Count: " & i & "</p>"
For j = 0 to i - 1
Response.Write "<p>aryNotificationIDs(" & j & ") = " & aryNotificationIDs(j) & "</p>"
Next
End If

Related

Exclude certain selections from a drop down list ASP

I'm working on a ASP (Within the payment gateway). The options in the drop down at being pulling in from a database. I can't touch the database so have to attack the matter from the code.
Here is the value name that I need to exclude _01BM(Q)
Here is the code for the drop down.
<select name="programgroup" onchange="onProgramGroup()">
<% Call buildDropDownList(strProgramGroupCode, rsProgramGroup, "ProgramGroupCode", "ProgramGroupDescription", False)%>
</select>
I would really appreciate any help on this guys.
Here is the code for the method:
Sub buildDropDownList(strCurrentSelection, objListData, strCodeName, strDescriptionName, blnIncludeOther)
If Not objListData.BOF Then
objListData.MoveFirst
End If
While Not objListData.EOF
Response.Write "<option value='" & objListData(strCodeName) & "' "
If StrComp(strCurrentSelection, objListData(strCodeName),1) = 0 then
Response.Write "selected"
End If
Response.Write ">" & objListData(strDescriptionName) & "</option>" & VbCrLf
objListData.MoveNext
Wend
if blnIncludeOther then
Response.Write "<option value='<Other>' "
If strCurrentSelection <> "" and InStr(1, "<Other>", strCurrentSelection) = 1 then
Response.Write "selected"
End If
Response.Write ">Other</option>" & VbCrLf
end if
End Sub
You will have to change the method building the drop down. Since you did not provide us with the code for it, I'll give you a skeleton, and can use it to change your actual code.
To make it more generic and less ugly, better pass the value(s) to exclude to the method, as an array, instead of hard coding them in there.
So, the method should look like this:
Sub buildDropDownList(strProgramGroupCode, rsProgramGroup, someParamHere, anotherParam, boolParam, arrValuesToExclude)
Dim excludedValuesMapping, x
Set excludedValuesMapping = Server.CreateObject("Scripting.Dictionary")
For x=0 To UBound(arrValuesToExclude)
excludedValuesMapping.Add(LCase(arrValuesToExclude(x)), True)
Next
'...unknown code here...
Do Until rsProgramGroup.EOF
strCurrentValue = rsProgramGroup(valueFieldName)
If excludedValuesMapping.Exists(LCase(strCurrentValue)) Then
'value should be excluded, you can do something here, but not write it to browser
Else
strCurrentText = rsProgramGroup(textFieldName)
Response.Write("<option value=""" & Replace(strCurrentValue, """", """) & """>" & strCurrentText & "</option>")
End If
rsProgramGroup.MoveNext
Loop
End Sub
And to use it:
<% Call buildDropDownList(strProgramGroupCode, rsProgramGroup, "ProgramGroupCode", "ProgramGroupDescription", False, Array("_01BM(Q)"))%>
Now having your code, and if you don't want to make it generic, you can also ignore specific values by having such code in the buildDropDownList sub:
Dim currentCodeValue
While Not objListData.EOF
currentCodeValue = objListData(strCodeName)
If (UCase(currentCodeValue)<>"_04GIDBM") And _
(UCase(currentCodeValue)<>"_05GIDFM") And _
(UCase(currentCodeValue)<>"_08EXHRM") And _
(UCase(currentCodeValue)<>"_10EXMKT") And _
(UCase(currentCodeValue)<>"_12EXTTH") And _
(UCase(currentCodeValue)<>"_17EXHSC") Then
Response.Write "<option value='" & currentCodeValue & "' "
If StrComp(strCurrentSelection, currentCodeValue, 1) = 0 then
Response.Write "selected"
End If
Response.Write ">" & objListData(strDescriptionName) & "</option>" & VbCrLf
End If
objListData.MoveNext
Wend
This will just skip any records with such values, and will not output a drop down option for them.

Cannot apply operator && to operands of type String and String()

I'm having cannot apply operator && to operands of type String and String() at the below code. Anyone knows what's the cause for this issue?
If IsValidEmail(EmailAddress) Then
EncodedData += "&data[]=" +
+ HttpContext.Current.Server.UrlEncode( _
(Convert.ToString((Convert.ToString("{""email"":""") _
& EmailAddresses) + """,""name"":""") & Name) + """}")
End If
If EmailAddresses is an array, you have to decide how to combine the potentially multiple values in there.
Maybe, something like:
String.Join(";",EmailAddresses)
So that the addresses are ; separated? Or maybe, since this is inside an If block that checks a different, but probably related variable, you intended this reference to be EmailAddress, not EmailAddresses.
So, either:
EncodedData += "&data[]=" _
& HttpContext.Current.Server.UrlEncode("{""email"":""" _
& String.Join(";",EmailAddresses) & """,""name"":""" _
& Name & """}")
or:
EncodedData += "&data[]=" _
& HttpContext.Current.Server.UrlEncode("{""email"":""" _
& EmailAddress & """,""name"":""" _
& Name & """}")
Where I've also removed the pointless conversions of strings into (better?) strings and the mixing of string concatenation operators.

Entering each row of datagrid into SQL database

I'm attempting to take a column from each row of my datagrid and enter it into an SQL database. Having all sorts of problems/errors making it work.
This is the most current version:
For i = 0 to agentGridView.Rows.Count - 1
varAgt = agentGridView.Rows(i).Cells(1).Text
strSQL = "INSERT INTO tblAgentVisitAgents (VisitID, AgtID)" & _
" Values (" & _
VisitID.Text & "," & _
varAgt & ")"
strSQL = Utils.replaceChars(strSQL)
DAL.ExecNonQuery(strSQL, CommandType.Text)
Next
EDIT: The issue is that my cell(1) is a hidden field. When I make it visible, the entry form works. When it's hidden, it won't enter anything and thus gives me a syntax error. Is there a way I can use a hidden field for entry purposes?
You need to use Text instead of Value . Like following.
varAgt = agentGridView.Rows(i).Cells(1).Text instead of varAgt = agentGridView.Rows(i).Cells(1).Value
But if you have that control in a Label, then you need to typecast to label and then use Text. E.g.
varAgt = CType(agentGridView.Rows(i).Cells(1).FindControl("controlID"),Label).Text -- replace controllID with required label id.
Source - http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
Here's what I went with:
Front:
<asp:GridView ID="agentGridView" DataKeyNames="agentName,agentValue" ... />
Back:
For i = 0 to agentGridView.Rows.Count - 1
varAgt = agentGridView.DataKeys(i).Values("agentValue").ToString
strSQL = "INSERT INTO tblAgentVisitAgents (VisitID, AgtID)" & _
" Values (" & _
VisitID.Text & "," & _
varAgt & ")"
strSQL = Utils.replaceChars(strSQL)
DAL.ExecNonQuery(strSQL, CommandType.Text)
Next
Source (for C#): Hide BoundField's but still be able to get values with C#

ASP.net SQL database amend existing string field data using command parameters

I am trying to maintain a log field (fldUserLog ) of my database table so that when updating each raw, the log field will be amended with given log string.
Log string
strUserLog = "Added by : " & Session("auth_Id") & " at " & Now() & " from IP " &
Request.ServerVariables("REMOTE_ADDR") & vbCrLf
and I am using SQL command parameters to UPDATE query. as follows
strSQLQuery = "UPDATE myTable SET " _
& "fldTitle = #xTitle, " _
& "fldDesc = #xDesc, " _
& "fldUserLog = fldUserLog + #xUserLog " _
& "WHERE fldId = #xId ;"
strMessage = "updated"
ObjAddDB.setCommand(strSQLQuery)
With ObjAddDB
.setParameters("#xTitle", frmTitle.Text)
.setParameters("#xDesc", frmDesc.Text)
.setParameters("#xUserLog", strUserLog)
.setParameters("#xId", MyItemId)
End With
Please note that setCommand and setParameters are my own methods I am using in my database.vb class file.
I get following error when its executed
Exception Details:
System.Data.SqlClient.SqlException:
Incorrect syntax near 'fldUserLog'.
please help me to use my UPDATE query to amend existing data with command parameters.
If the format of the fldUserLog field value contains spaces, you need to embrace the value with [ ] ..
& "fldUserLog = [fldUserLog #xUserLog] " _
I guess what you may want to write is the following:
& "fldUserLog = #xUserLog " _

ASP - Printing the entire request contents

I'm debugging some ASP code and I need to get a quick printout of the current Request datastructure, which I believe is an array of key/value pairs.
I see that Request.Form("key") is the method for extracting individual elements.
Any tips on printing out the entire thing?
Try this
For Each item In Request.Form
Response.Write "Key: " & item & " - Value: " & Request.Form(item) & "<BR />"
Next
Working:
For x = 1 to Request.Form.Count
Response.Write x & ": " _
& Request.Form.Key(x) & "=" & Request.Form.Item(x) & "<BR>"
Next
I have other Classic ASP code snippets here:
https://github.com/RaviRamDhali/programming-procedure/tree/master/Snippets/ASP
Try a FOR/EACH loop:
for each x in Request.Form
Response.Write(x)
Next

Resources