我有一个像这样的 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>
我需要找到元素 doc 的序号位置,其中子节点 arr/id 的文本值为 2
我正在使用经典 ASP
谢谢
最佳答案
使用例如
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。
关于xml - 如何使用 VBScript 和 XPATH 查找 XML 中元素的序号位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2681431/