Search code examples
xmlxpathasp-classicvbscript

How to find ordinal position of an element in XML using VBScript & XPATH


I have an XML like this

<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader">
    <int name="status">0</int>
    <int name="QTime">1</int>
    <lst name="params">
        <str name="start">num</str>
        <str name="fl">string</str>
        <str name="q">string</str>
        <str name="rows">num</str>
        <str name="op">string</str>
        <str name="sort">string</str>
    </lst>
</lst>
<result name="response" numFound="20" start="1">
    <doc>
        <arr name="URL"><str>string</str></arr>
        <arr name="ID"><int>1</int></arr>
    </doc>
    <doc>
        <arr name="URL"><str>string</str></arr>
        <arr name="ID"><int>2</int></arr>
    </doc>  
    <doc>
        <arr name="URL"><str>string</str></arr>
        <arr name="ID"><int>3</int></arr>
    </doc>      
    <doc>
        <arr name="URL"><str>string</str></arr>
        <arr name="ID"><int>4</int></arr>
    </doc>      
</result>
</response>

I need to find the ordinal position of element doc which child node arr/id has text value 2

I am Using Classic ASP

thanks


Solution

  • Use e.g.

    Set doc = Server.CreateObject("Msxml2.DOMDocument.3.0")
    doc.async = False
    If doc.load(Server.MapPath("input.xml")) Then
      doc.setProperty "SelectionLanguage", "XPath"
      Set docEl = doc.selectSingleNode("response/result/doc[arr[@name = 'ID'] = 2]")
      If Not(doc Is Nothing) Then
        Response.Write(docEl.selectNodes("preceding-sibling::doc").length)
      Else
        Response.Write("Not found.")
      End If
    Else
      Response.Write doc.parseError.reason
    End If
    

    As already pointed out, if you want the index to start with 1 and not 0 then you need to add 1 to the result.