Hi i have a xml file on the web and i would like to scrape it to get the relevant information
<M MId="1195772" LId="34923" _LId="34921" OId="569" SId="5" KId="122" LNr="2" C0="1392715800" ML="1" HId="13106" GId="5996" W="" HN="Musfat Banyas" GN="Omyyah Idlib" HRC="" HRCi="1" GRC="" GRCi="0" Info="" S1="1-1" S2="1-0" MStan="1" OTv="" L="0" A="3" Ao="11"/>
I would like to scrape every M and get the value of HN GN S1 S2
I have tried using the below code but i dont get any values returned
Imports System.Net
Imports System.IO
Imports System.Xml
Imports HtmlAgilityPack
Partial Class Grayhounds_home
Inherits System.Web.UI.Page
' Gettodaysmatches(cominguptable, "https://www.betfair.com/sport/football?selectedTabType=TODAY", ".//div[contains(#class, 'match event-information ui-event')]", ".//span[#class='home-team-name']", ".//span[#class='away-team-name']", ".//span[#class='ui-no-score']")
Private Sub Grayhounds_home_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim webGet As New HtmlWeb() 'open the system
Dim htmlDoc As HtmlDocument = webGet.Load("http://www.futbol24.com/matchDayXml/?Day=20140218") '' get the html from the webpage
Dim coll As HtmlNodeCollection = htmlDoc.DocumentNode.SelectNodes("//m")
If coll IsNot Nothing Then
For Each div As Object In coll ' select all the divs wi
test.Text = div.Attributes("HN").Value
Next
End If
End Sub
End Class
You have better options for parsing XML files, by using .NET built-in classes : XDocument or XmlDocument. For example, using XmlDocument :
Dim doc As New XmlDocument
doc.Load("http://www.futbol24.com/matchDayXml/?Day=20140218")
Dim coll = doc.SelectNodes("//M")
For Each M As XmlNode In coll
test.Text = M.Attributes("HN").Value
Next
Related
I am learning ASP.Net development & trying to create Web application where ListView data should get filter selection done in ComboBox. I have made ListView & bind it with my database table & tried to put ComboBox filter but getting this error
(System.Web.HttpException: Request is not available in this context) in output .
VB Code
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Partial Class VB
Inherits System.Web.UI.Page
Dim query As String
Dim strArea As String = Request.QueryString("Country")
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindListView()
End If
End Sub
Private Sub BindListView()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT CustomerId, ContactName, Country FROM Customers"
cmd.Connection = con
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
lvCustomers.DataSource = dt
lvCustomers.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub OnPagePropertiesChanging(sender As Object, e As PagePropertiesChangingEventArgs)
TryCast(lvCustomers.FindControl("DataPager1"), DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, False)
Me.BindListView()
End Sub
Protected Sub country_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles country.SelectedIndexChanged
Try
If country.SelectedValue <> "All" Then
query = "Select CutomerId, Contact Name, Country from Customers where Country like '%" + strArea + "%' order by rank;"
End If
Dim cmd As New SqlCommand(query)
Dim da As New SqlDataAdapter(cmd)
Dim table As New DataTable
Catch ex As Exception
End Try
End Sub
End Class
Request read-only property belongs to Page class and inherited class members are available only within the members of the class which inherits it(VB in your case). Change your code like this:-
Partial Class VB
Inherits System.Web.UI.Page
Dim query As String
Dim strArea As String = String.Empty
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindListView()
End If
strArea = Request.QueryString("Country")
End Sub
Also, Please note it will be better to check if any value exists within your query string variable before assigning it.
I Tried to delete blank rows from excel using the code
Dim wb As New Workbook("d:\test\book1.xls")
Dim sheets As WorksheetCollection = wb.Worksheets
Dim sheet As Worksheet = sheets(0)
sheet.Cells.DeleteBlankRows()
wb.Save("d:\test\mybook.xls")
But i am getting syntax error.Any one know the Namespace requiered to do this?
Try
ApplicationClass excel = new ApplicationClass();
Microsoft.Office.Interop.Excel.Range cellToBeDeleted = (Range)excel.Cells[rowIndex, columnIndex];
cellToBeDeleted.Delete();
Include the following namespace
using Excel = Microsoft.Office.Interop.Excel;
Try This
-Add Reference (from COM section ) Micsrosoft Excel Object Library to your project
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
delBlankRows("d:\test\book1.xls", 1)
End Sub
Private Sub delBlankRows(ByVal excelFileName As String, sheetIndex As Integer)
Dim excel As Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application
Dim fileName = excelFileName
Dim w As Workbook = excel.Workbooks.Open(fileName)
Dim r As Range = w.Worksheets(sheetIndex).UsedRange.EntireRow.SpecialCells(XlCellType.xlCellTypeBlanks)
r.Delete()
w.Save()
w.Close()
End Sub
End Class
I am a total beginner at VB.NET so you may need to bear with me but I need to edit this code behind so that a null value is passed to my database for the 'imageurl' field. The front end is a web form where a user can enter details of a book, with the option of uploading a book cover.
I want to change my code so that if the file upload dialog does not fulfil hasFile, the GUID string generated in the database will be a NULL value (this is so I can have a 'no image available' image using the NullImageUrl property in ASP.)
This is what I've tried to implement so far, but intellisense is telling me that "Value of type String cannot be converted to 'System.GUID'.
Code Behind:
Imports System.Data.OleDb
Partial Public Class addBook
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btn_submission_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submission.Click
Dim noFile As String = Nothing
Dim myGUID = Guid.NewGuid()
Dim newFileName As String = myGUID.ToString() & ".jpg"
Dim fileLocationOnServerHardDisk = Request.MapPath("img/thumb") & "/" & newFileName
If fu_picture.HasFile Then
fu_picture.SaveAs(fileLocationOnServerHardDisk)
Else
myGUID = noFile
End If
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into booklist(Title,Author,PublicationDate,Pages,Publisher,Blurb,imgurl,AverageRating)
Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7,#f8)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_booktitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_bookauthor.Text)
cmd.Parameters.AddWithValue("#f3", tb_bookpubyear.Text)
cmd.Parameters.AddWithValue("#f4", tb_bookpages.Text)
cmd.Parameters.AddWithValue("#f5", tb_publisher.Text)
cmd.Parameters.AddWithValue("#f6", tb_blurb.Text)
cmd.Parameters.AddWithValue("#f7", "img/thumb/" & newFileName)
cmd.Parameters.AddWithValue("#f8", rbl_Stars.SelectedValue)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/addedrecord.aspx")
End Sub
Protected Sub rbl_Stars_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rbl_Stars.SelectedIndexChanged
End Sub
End Class
Please tell me if I'm completely wrong in my line of thinking!
EDIT: At this present moment, even if a file is not uploaded, a guid string + jpg suffix are generated in the database table even if the image itself doesn't exist
You should pass DBNull.Value to your db if you fail the requirement
cmd.Parameters.AddWithValue("#f7", _
if(fu_picture.HasFile, "img/thumb/" & newFileName, DbNull.Value)
The ternary operator allows you to test the flag HasFile just when you create the parameter.
If it is false you set the parameter value to DBNull.Value. If HasFile is true you can build the correct path to your imagefile. Of course this removes the necessity to assign Nothing to myGuid in the code before.
I need help with the following issue. I parse XML and do a XSLT transformation. Everything is fine with Stylus Studio. But with ASP.NET I can't parse and output.
min.aspx.vb
Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.Xsl
Imports System.IO
Partial Class Poseidon_min
Inherits System.Web.UI.Page
Protected Sub Literal1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Literal1.PreRender
Dim strXSLTFile As String = "http://www.kiris-alinda.de/Poseidon/Hotelangebote.xslt"
Dim strXMLFile As String = "http://www.kiris-alinda.de/Poseidon/PosXMLReq/PosXMLReqSearch.php?htc=AYTLIND"
Dim reader As XmlReader = XmlReader.Create(strXMLFile)
Dim objXSLTransform As New XslCompiledTransform()
objXSLTransform.Load(strXSLTFile)
Dim htmlOutput As New StringBuilder()
'Dim htmlWriter As TextWriter = New StringWriter(htmlOutput)
'objXSLTransform.Transform(reader, Nothing, htmlWriter)
Me.Literal1.Text = htmlOutput.ToString()
reader.Close()
End Sub
End Class
Why is it not possible to output <xsl:value-of select="PosXmlResponse/search/date/#min"/> from the XSLT in ASP.NET?
Take a look at this :
XML / XSLT Transformation
You have to use an XML Server Control on the ASPX page and then setting up XSLT Transformation
I use this code:
Public Shared Function Transform(xml As String, xsl As String, argsList As XsltArgumentList) As String
Dim selectedXml As XDocument = XDocument.Parse(xml)
Dim xmlTransform As New XslCompiledTransform()
Dim htmlOutput As New StringBuilder()
Dim writer As XmlWriter = XmlWriter.Create(htmlOutput)
xmlTransform.Load(New XmlTextReader(New StringReader(xsl)))
xmlTransform.Transform(selectedXml.CreateReader(), argsList, writer)
Return htmlOutput.ToString()
End Function
I am trying to set up a page that will allow the user to browse a file directory on the Web server.
The aim is to allow users to drop files within a given directory structure and the code will create the tree view based off the directory.
When setting the Nodes Navigate URL it maps to the C:\Staging\Files which obvioulsy does not work on the web. I would need to map to http://webaddress/staging/files etc
Here is the offending code
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'
Dim rootDir As New DirectoryInfo("C:\Staging\")
' Enter the RecurseNodes function to recursively walk the directory tree.
Dim RootNode As TreeNode = RecurseNodes(rootDir)
' Add this Node hierarchy to the TreeNode control.
Treeview1.Nodes.Add(RootNode)
End If
End Sub
Private Function RecurseNodes(ByVal thisDir As DirectoryInfo) As TreeNode
Dim thisDirNode As New TreeNode(thisDir.Name, Nothing)
' Get all the subdirectories in this Directory.
Dim subDirs As DirectoryInfo() = thisDir.GetDirectories()
For Each subDir As DirectoryInfo In subDirs
thisDirNode.ChildNodes.Add(RecurseNodes(subDir))
Next
' Now get the files in this Directory.
Dim files As FileInfo() = thisDir.GetFiles()
For Each file As FileInfo In files
Dim thisFileNode As New TreeNode(file.Name, Nothing)
**thisFileNode.NavigateUrl = file.FullName**
thisDirNode.ChildNodes.Add(thisFileNode)
Next
Return thisDirNode
End Function
I think you should take the reverse approach. Rather than getting contents of a physical path on disk, try using Server.MapPath to grab contents of a virtual path combine it with a base URL:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim RootNode As TreeNode = RecurseNodes("~/files")
TreeView1.Nodes.Add(RootNode)
End If
End Sub
Private Overloads Function RecurseNodes(ByVal virtualPath As String) As TreeNode
If Not VirtualPathUtility.IsAbsolute(virtualPath) Then virtualPath = VirtualPathUtility.ToAbsolute(virtualPath)
virtualPath = VirtualPathUtility.RemoveTrailingSlash(virtualPath)
Dim baseUrl As String = Request.Url.GetLeftPart(UriPartial.Authority) + virtualPath
Return RecurseNodes(New DirectoryInfo(Server.MapPath(virtualPath)), baseUrl)
End Function
Private Overloads Function RecurseNodes(ByVal thisDir As DirectoryInfo, ByVal baseUrl As String) As TreeNode
Dim thisDirNode As New TreeNode(thisDir.Name, Nothing)
Dim subDirs As DirectoryInfo() = thisDir.GetDirectories()
For Each subDir As DirectoryInfo In subDirs
thisDirNode.ChildNodes.Add(RecurseNodes(subDir, baseUrl + subDir.Name + "/"))
Next
Dim files As FileInfo() = thisDir.GetFiles()
For Each file As FileInfo In files
Dim thisFileNode As New TreeNode(file.Name, Nothing)
thisFileNode.NavigateUrl = baseUrl + file.Name
thisDirNode.ChildNodes.Add(thisFileNode)
Next
Return thisDirNode
End Function