只在ASP中循环具有特定属性的XML元素
问题描述:
我只想循环具有属性New =“True”的元素 - 而不是在循环内部使用If语句。这怎么可能? (我希望这将提供更好的性能)只在ASP中循环具有特定属性的XML元素
ASP:
<%
Set objXMLDoc = Server.CreateObject("MSXML2.DOMDocument.3.0")
objXMLDoc.async = False
objXMLDoc.load Server.MapPath("/data.xml")
Dim xmlProduct
For Each xmlProduct In objXMLDoc.documentElement.selectNodes("Product")
Dim productCode : productCode = xmlProduct.selectSingleNode("ProductCode").text
Dim productName : productName = xmlProduct.selectSingleNode("ProductName").text
Response.Write Server.HTMLEncode(productCode) & " - "
Response.Write Server.HTMLEncode(productName) & "<br>"
Next
%>
XML:
<Products>
<Product New="True">
<ProductCode>1234</ProductCode>
<ProductName>Bike</ProductName>
</Product>
<Product New="False">
<ProductCode>1235</ProductCode>
<ProductName>Car</ProductName>
</Product>
<Product New="True">
<ProductCode>1236</ProductCode>
<ProductName>Plane</ProductName>
</Product>
</Products>
答
可以查询和使用XPATH筛选XML文档:
Dim xpath : xpath = "/*/Product[@New='True']"
Dim xml
Set xml = CreateObject("Msxml2.DOMDocument")
xml.async = False
xml.loadXML([YOUR XML STRING])
Dim root, xmlNodes, x
Set root = xml.documentElement
set xmlNodes = xml.selectNodes(xpath)
If xmlNodes.length > 0 then
For each x in xmlNodes
response.write(x.text)
Next
Else
response.write("not found.")
End if
set xmlNodes = nothing
Set root = Nothing
Set xml = Nothing
我已经在你的XML结构上测试了这个xpath,它似乎工作。有关xpath语法的更多信息是here。
HTH, Erik
当然!谢谢! – NinjaFart