I'm receiving an xml response and I now want to parse this.
Currently what I have to receive the XML response is:
Dim textReader = New IO.StreamReader(Request.InputStream)
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim Xmlin = XDocument.Load(textReader)
How can I go ahead now a process this and pick out the element values?
<subscription>
<reference>abc123</reference>
<status>active</status>
<customer>
<fname>Joe</fname>
<lname>bloggs</lname>
<company>Bloggs inc</company>
<phone>1234567890</phone>
<email>joebloggs#hotmail.com</email>
</customer>
</subscription>
If I have it in string format I can do this using
Dim xmlE As XElement = XElement.Parse(strXML) ' strXML is string version of XML
Dim strRef As String = xmlE.Element("reference")
Do I need to convert the request.inputstream to a strign format or is there another better way?
Thanks
Do I need to convert the request.inputstream to a strign format or is there another better way?
You could directly load it from the request stream, you don't need to convert it to a string:
Request.InputStream.Position = 0
Dim Xmlin = XDocument.Load(Request.InputStream)
Dim reference = Xmlin.Element("subscription").Element("reference").Value
or:
Dim reference = Xmlin.Descendants("reference").First().Value
In the end after much testing I could only get this to work:
Dim textReader = New IO.StreamReader(Request.InputStream)
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim Xmlin = XDocument.Load(textReader)
Dim strXml As String = Xmlin.ToString
Dim xmlE As XElement = XElement.Parse(strXml)
Dim strRef As String = xmlE.Element("reference")
Dim strStatus As String = xmlE.Element("status")
Dim strFname As String = xmlE.Element("customer").Element("fname").Value()
Dim strLname As String = xmlE.Element("customer").Element("lname").Value()
Dim strCompany As String = xmlE.Element("customer").Element("company").Value()
Dim strPhone As String = xmlE.Element("customer").Element("phone").Value()
Dim strEmail As String = xmlE.Element("customer").Element("email").Value()
Related
I am trying to download a webpage as string. Can someone please explain why the following code doesn't work?
Dim URL As String = "http://stackoverflow.com/"
Dim client As WebClient = New WebClient()
Dim data As Stream = client.OpenRead(URL)
Dim reader As StreamReader = New StreamReader(data)
Dim str As String = ""
str = reader.ReadLine()
Do While str.Length > 0
Console.WriteLine(str)
str = reader.ReadLine()
Loop
When I run it it never goes inside the loop.
Give this a shot...
Dim URL As String = "http://stackoverflow.com/"
Dim html As String = New WebClient().DownloadString(URL)
Better Solution (Releases resources that the network stack is using. Also ensure's (hope) the CLR cleans these up when needed.)
Using client As New WebClient()
html = client.DownloadString(URL)
End Using
So if i run this code i'm thrown a multi-part identifier errorregarding the binding of the textbox "clid"
Can somebody please help to resolve this issue?
Using cnnentry As New SqlConnection("Data Source=NB-1492\sqlipt;Initial Catalog=Bookings;Integrated Security=True;Pooling=False")
Dim entrclientid As String
Dim clid As New TextBox
clid = FormView1.FindControl("txtclientid")
entrclientid = Convert.ToString(clid)
Dim sqlentry1 As String = "INSERT INTO BOOKING_DETAILS(CLIENT_ID) VALUES("
Dim sqlentry2 As String = entrclientid
Dim sqlentry3 As String = ")"
Dim sqlentry4 As String = sqlentry1 & sqlentry2 & sqlentry3
Dim cmdclientid As New SqlCommand(sqlentry4, cnnentry)
cnnentry.Open()
string1 = cmdclientid.ExecuteNonQuery()
cnnentry.Close()
End Using
Thanks in advance
P.S. please excuse the naming conventions i wrote this extremely quickly
You don't want to convert the TextBox to a String but it's Text property:
change
entrclientid = Convert.ToString(clid)
to
entrclientid = clid.Text
But more important, you should use sql-parameters to prevent sql-injection.
Dim sql As String = "INSERT INTO BOOKING_DETAILS(CLIENT_ID) VALUES(#CLIENT_ID)"
Dim cmdclientid As New SqlCommand(sql, cnnentry)
cmdclientid.Parameters.AddWithValue("#CLIENT_ID", clid.Text)
I am posting to a website to get data back. The site returns it as an xml. I am able to get the data into a string. But what i really want to do is to have each item in the xml in a different string field.
Sub lookup(ByVal Source As Object, ByVal e As EventArgs)
Dim wData As String
wData = WRequest("http://PostToThisSite.com", "POST","str=31&Password=pn&UserID=Q&Postcode="+txtPcode.Text)
Response.Write(wData)
End Sub
Function WRequest(URL As String, method As String, POSTdata As String) As String
Dim responseData As String = ""
Try
Dim hwrequest As Net.HttpWebRequest = Net.Webrequest.Create(URL)
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = true
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = 60000
hwrequest.Method = method
If hwrequest.Method = "POST" Then
hwrequest.ContentType = "application/x-www-form-urlencoded"
Dim encoding As New Text.ASCIIEncoding() 'Use UTF8Encoding for XML requests
Dim postByteArray() As Byte = encoding.GetBytes(POSTdata)
hwrequest.ContentLength = postByteArray.Length
Dim postStream As IO.Stream = hwrequest.GetRequestStream()
postStream.Write(postByteArray, 0, postByteArray.Length)
postStream.Close()
End If
Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Dim responseStream As IO.StreamReader = _
New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End If
hwresponse.Close()
Catch e As Exception
responseData = "An error occurred: " & e.Message
End Try
Return responseData
End Function
The above code works and writes out a line...
Some Road City LU1 5QG
The Xml being returned is ..
<Address xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://site.co.uk/">
<strOrganisation />
<strProperty />
<strStreet>Some Road</strStreet>
<strLocality />
<strTown>City</strTown>
<strCounty />
<strPostcode>LU1 5QG</strPostcode>
<strDPS />
I want to be able to split these fields and set them to different text boxes on the page...help?
Load the xml string into an XmlDocument and extract the values with XPath:
Dim doc = new XmlDocument()
doc.LoadXml(yourXmlString)
Dim nsm = new XmlNamespaceManager(doc.NameTable)
nsm.AddNamespace("a", "http://site.co.uk/")
txtStreet.Text = doc.SelectSingleNode("/a:Address/a:strStreet", nsm).InnerText
Here's a working snippet:
Dim doc = New XmlDocument()
doc.LoadXml("<Address xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://site.co.uk/""><strOrganisation /> <strProperty /> <strStreet>Some Road</strStreet> <strLocality /> <strTown>City</strTown> <strCounty /> <strPostcode>LU1 5QG</strPostcode><strDPS /></Address>")
Dim nsm = New XmlNamespaceManager(doc.NameTable)
nsm.AddNamespace("a", "http://site.co.uk/")
Dim streetValue = doc.SelectSingleNode("/a:Address/a:strStreet", nsm).InnerText
Some things to note:
For XPath lookups, if your xml has a namespace you'll need to add it to an
XmlNameSpaceManager created from your XmlDocument's NameTable.
If you don't want to
bother with that, you can walk the node collections manually via
doc.ChildNodes[0].ChildNodes[0] etc.
Or try this, which is what I believe the author was asking.
' Use XML Reader
Dim xmlDoc = New XmlDocument
Dim xmlNode As Xml.XmlNode
xmlDoc.LoadXml(strResponse)
xmlNode = xmlDoc.SelectSingleNode("//" + "strStreet")
If Not xmlNode Is Nothing Then
Dim Street = xmlNode.InnerText
End If
Using ASP/VB, I'm trying to get rid of some duplication in a list box that is coming from an XML document.
Sorry if this is a daft question, I'm new to this.
I've tried various things, but nothing has worked. Here is the code - thanks for any help / assistance!
Function getAssets(ByVal siteid As String) As String
Dim oAssets As New Xteam.XteamWebService
Dim strAssets As String = ""
Dim oDoc As New XmlDocument
'Dim oNode As XmlNode
strAssets = oAssets.ReadHAssetCodes(siteid)
oDoc.LoadXml(strAssets)
For Each Node As XmlNode In oDoc.SelectSingleNode("XteamAssets")
lstHAssets.Items.Add(New ListItem(Node("hassetdescription").InnerText, Node("hassetcode").InnerText))
Next
lstHAssets.Items.Insert(0, "--Please Select--")
Return "ToSender"
End Function
There's probably a more efficient way but this will work.
Function getAssets(ByVal siteid As String) As String
Dim oAssets As New Xteam.XteamWebService
Dim strAssets As String = ""
Dim oDoc As New XmlDocument '
Dim oNode As XmlNode
strAssets = oAssets.ReadHAssetCodes(siteid)
oDoc.LoadXml(strAssets)
Dim strAryUniqueValues as string()
Dim strUniqueValues as string = ""
Dim i as int = 0
Dim strSearchPair as string
For Each Node As XmlNode In oDoc.SelectSingleNode("XteamAssets")
strSearchPair = "~" & Node("hassetdescription").InnerText & "/" & Node("hassetcode").InnerText & "~"
' see if these values have been included already, if not then add them
if instr(strUniqueValues,strSearchPair) = -1 then
strAryUniqueValues(i) = strSearchPair
strUniqueValues = strUniqueValues & strAryUniqueValues(i)
i = i + 1
end if
Next
'now loop back through and build your listbox
Dim strAryPair as string()
For each strPair in strAryUniqueValues
strAryPair = split(strPair,"/")
lstHAssets.Items.Add(New ListItem(Replace(strAryPair(0),"~",""),Replace(strAryPair(1),"~",""))
Next
lstHAssets.Items.Insert(0, "--Please Select--")
Return "ToSender"
End Function
Hi can any one help me out for this.
I have RDLC Report displayed on my web page using asp.net And C#.net I want to export it to PDF on button click.
Please can you help me?
Thanks
I did something like this a while ago. Below is the code I used in the page_load event of a page. It is in VB and isn't the best code in the world but might help you get a solution..
Dim jobid As Integer = Request("jobid")
Dim rv As New Microsoft.Reporting.WebForms.ReportViewer
Dim r As String = "apps/Reports/legal_document.rdlc"
Dim ds As New jobmanagerTableAdapters.JobInformationTableAdapter
Dim ds2 As New ordermanagementTableAdapters.RecoveryItemsInformationTableAdapter
Dim ds3 As New expensemanagerTableAdapters.tbl_expensesTableAdapter
Dim ds4 As New ordermanagementTableAdapters.tbl_orders_collection_itemsTableAdapter
Dim ds5 As New attachmentsmanagerTableAdapters.tbl_attachmentsTableAdapter
Dim ds6 As New notesmanagerTableAdapters.tbl_notesTableAdapter
Dim ds7 As New payments_managerTableAdapters.tbl_paymentsTableAdapter
Dim rptSource1 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource2 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource3 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource4 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource5 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptSource6 As New Microsoft.Reporting.WebForms.ReportDataSource
Dim rptsource7 As New Microsoft.Reporting.WebForms.ReportDataSource
rptSource1.Name = "jobmanager_JobInformation"
rptSource1.Value = ds.GetJobInfobyJobID(jobid)
rptSource2.Name = "ordermanagement_RecoveryItemsInformation"
rptSource2.Value = ds2.GetRecoveryItemsbyJobIDOrderID(jobid, 0)
rptSource3.Name = "expensemanager_tbl_expenses"
rptSource3.Value = ds3.GetExpensesbyJobIDOrderID(jobid, 0)
rptSource4.Name = "ordermanagement_tbl_orders_collection_items"
rptSource4.Value = ds4.GetDataByJobIDOrderID(jobid, 0)
rptSource5.Name = "attachmentsmanager_tbl_attachments"
rptSource5.Value = ds5.GetAllAttachmentsbyJobID(jobid)
rptSource6.Name = "notesmanager_tbl_notes"
rptSource6.Value = ds6.GetAllNotesbyJobID(jobid)
rptsource7.Name = "payments_manager_tbl_payments"
rptsource7.Value = ds7.GetPaymentsbyJobID(jobid)
rv.LocalReport.DataSources.Clear()
rv.LocalReport.ReportPath = r.ToString
rv.LocalReport.DataSources.Add(rptSource1)
rv.LocalReport.DataSources.Add(rptSource2)
rv.LocalReport.DataSources.Add(rptSource3)
rv.LocalReport.DataSources.Add(rptSource4)
rv.LocalReport.DataSources.Add(rptSource5)
rv.LocalReport.DataSources.Add(rptSource6)
rv.LocalReport.DataSources.Add(rptsource7)
'Page.Controls.Add(rv)
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim bytes As Byte()
'Get folder on web server from web.config
Dim FolderLocation As String
FolderLocation = Server.MapPath("reports")
'First delete existing file
Dim filepath As String = FolderLocation & "\legal.PDF"
File.Delete(filepath)
'Then create new pdf file
bytes = rv.LocalReport.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Dim fs As New FileStream(FolderLocation & "\legal.PDF", FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
fs.Close()
Response.Redirect("reports/legal.pdf")