f_atencia 0 Junior Poster in Training

<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<cd country="USA">
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<price>10.90</price>
</cd>
<cd country="UK">
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<price>9.90</price>
</cd>
<cd country="USA">
<title>Greatest Hits</title>
<artist>Dolly Parton</artist>
<price>12.90</price>
</cd>
</catalog>

Hi,

I'm sure it's very simple, but I'm new at ASP and XML. I just want to know how I can display the text of the last child in the code above onto an ASP web page. So in that case, it should display 12.90.

Thanks to all that can help

Dani AI

Generated

For : the simplest, reliable approach in Classic ASP is to use MSXML and an XPath expression that picks the last <cd> element. Load the XML with MSXML2.DOMDocument.6.0, check for parse errors, then select /catalog/cd[last()]/price and read its .text. That returns the last price without iterating every node.

<%
Dim xml
Set xml = Server.CreateObject("MSXML2.DOMDocument.6.0")
xml.async = False
If Not xml.load(Server.MapPath("catalog.xml")) Then
    Response.Write "XML load error: " & xml.parseError.reason
Else
    Dim priceNode
    Set priceNode = xml.selectSingleNode("/catalog/cd[last()]/price")
    If Not priceNode Is Nothing Then
        Response.Write Server.HTMLEncode(Trim(priceNode.text))
    Else
        Response.Write "Price node not found."
    End If
End If
%>

If XPath support is not preferred, a second option is to get a NodeList and index the last item:

<%
Dim cds
Set cds = xml.selectNodes("/catalog/cd")
If cds.length > 0 Then
    Dim lastCd, lastPrice
    Set lastCd = cds.item(cds.length - 1)
    Set lastPrice = lastCd.selectSingleNode("price")
    If Not lastPrice Is Nothing Then Response.Write Server.HTMLEncode(Trim(lastPrice.text))
End If
%>

Notes: use .text (not .xml), call Trim to remove stray whitespace, handle xml.parseError for diagnostics, and use Server.MapPath when loading a file. If the XML uses namespaces, set SelectionNamespaces before selecting nodes. MSXML supports XPath 1.0 so last() works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.