Asp XML feed reader
-
13-11-2019 - |
문제
What I have so far
I am creating a news feed for my site and I currently have this.
<%
TheFeed = "http://feeds.feedburner.com/Actsoft"
Set objXML = Server.CreateObject("Microsoft.XMLDOM")
objXML.Async = False
objXML.SetProperty "ServerHTTPRequest", True
objXML.ResolveExternals = True
objXML.ValidateOnParse = True
objXML.Load(TheFeed)
CellCount = 0
If (objXML.parseError.errorCode = 0) Then
Set objRoot = objXML.documentElement
If IsObject(objRoot) = False Then
Response.Write "There was an error retrieving the news feed"
Else
Set objItems = objRoot.getElementsByTagName("item")
If IsObject(objItems) = True Then
For Each objItem in objItems
On Error Resume Next
TheTitle = objItem.selectSingleNode("title").Text
TheLink = objItem.selectSingleNode("link").Text
Response.Write "<div class='article'>" &_
"<a href=" & TheLink & ">" & _
"<span>" & TheTitle & "</span>" & _
"</a>" & _
"</div>"
Next
End If
Set objItems = Nothing
End If
Else
Response.Write "There was an error retrieving the news feed"
End If
Set objXML = Nothing
%>
What I need out of this
I want to limit the amount of objects that are displayed in my reader. Right now every article is being displayed, and I want to limit by showing only the first 4.
I am new to Asp so I have no idea how to go about doing this.
해결책
Can be done with a counter in the for loop but I would like to use XPath.
Set the selection language to XPath.
objXML.SetProperty "ServerHTTPRequest", True
objXML.SetProperty "SelectionLanguage", "XPath"
Select the elements with
objXML.selectNodes("//item[position() <= 4]")
instead
objRoot.getElementsByTagName("item")
Then, first four will be displayed.
A suggestion about If IsObject(objItems) ... etc
:
The methods such like getElementsByTagName, selectNodes returns a collection of elements that have the specified name / expression.
If no nodes match the name / expression, returns an empty list / collection and it does not cause an error when you try to iterate it natively (For Each).
But, some selection methods returns a node object only (selectSingleNode, getNamedItem). If no node match, returns Nothing
.
The problem is that, Nothing
is an object too. Therefore IsObject(Nothing)
returns always true.
In such cases, you can handle like following.
'On Error Resume Next
Set TheTitle = objItem.selectSingleNode("title")
Set TheLink = objItem.selectSingleNode("link")
If TheTitle Is Nothing Then TheTitle = "" Else TheTitle = TheTitle.Text
If TheLink Is Nothing Then TheLink = "" Else TheLink = TheLink.Text