1

我想只循环具有属性 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>
4

1 回答 1

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 语法的更多信息在这里

HTH,埃里克

于 2013-08-02T12:10:59.047 回答