只在ASP中循环具有特定属性的XML元素

时间:2013-08-02 09:30:20

标签: xml loops asp-classic

我想只循环使用New =“True”属性的元素 - 而不是在循环中使用If语句。怎么可能? (我希望这能带来更好的表现)

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>

1 个答案:

答案 0 :(得分:2)

您可以使用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, 埃里克