开发者

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

开发者 https://www.devze.com 2022-12-27 10:37 出处:网络
I have an XML like this <?xml version=\"1.0\" encoding=\"UTF-8\"?> <response> <lst name=\"responseHeader\">

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


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.


You can't directly, you must count nodes. I would do

Dim xpath, docNode, position

xpath = "/response/result/doc[arr[@name='ID'] = 2]"
Set docNode = XmlDoc.SelectSingleNode(xpath)

If docNode Is Nothing  ' i.e. not found
  position = 0
Else
  position = docNode.SelectNodes("./preceding-sibling::doc").Length + 1
End If
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号