如何使用VBScript& amp;在XML中查找元素的序号位置XPATH

时间:2010-04-21 08:48:02

标签: xml xpath asp-classic vbscript

我有这样的XML

<?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>

我需要找到子节点arr / id具有文本值2的元素doc的序号位置

我正在使用经典ASP

感谢

2 个答案:

答案 0 :(得分:2)

你不能直接,你必须统计节点。我会做的

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

答案 1 :(得分:2)

使用例如

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

如前所述,如果您希望索引以1开头而不是0,则需要在结果中加1。