2016-11-26 76 views
-1

我需要解析一個包含大量產品的.xml文件,並且我需要它來返回所有在.xml文件中找到的產品。解析xml不循環?

但是,我只返回這些產品中的一種,即使它們位於.xml文件中,也不會觸及其他產品。

這是我的代碼,有人可以幫我解決這個問題嗎?

public void parse(String fileName) throws SAXException, IOException, XPathExpressionException { 
    File f = new File(fileName); 
    Document doc = builder.parse(f); 

    int prodCount = Integer.parseInt(path.evaluate("count(/inventory/products)", doc)); 

    for (int i = 1; i <= prodCount; i++) { 

     String code = path.evaluate("/inventory/products[" + i + "]/product/code", doc); 
     String description = path.evaluate("/inventory/products[" + i + "]/product/desc", doc); 
     Double price = Double.parseDouble(path.evaluate("/inventory/products[" + i + "]/product/price", doc)); 
     int quantity = Integer.parseInt(path.evaluate("/inventory/products[" + i + "]/product/quantity", doc)); 

     Product p = new Product(code, description, price, quantity); 
     products.add(p); 

    } 

    } 
} 

謝謝!

回答

1

首先,您要計算products元素的數量,而不是product元素。這總是1.正確的計數是

"count(/inventory/products/product)" 

您還需要將索引放置在子元素上,而不是父級。

例如

"/inventory/products/product[" + i + "]/code" 

"/inventory/products[" + i + "]/product/code" 

您可以通過直接與product節點工作簡化這個顯著:

NodeList products = (NodeList) path.evaluate("/inventory/products/product", doc, XPathConstants.NODESET); 

for (int i = 0; i < products.getLength(); i++) { 
    Node product = products.item(i); 
    String code = path.evaluate("code", product); 
    String description = path.evaluate("desc", product); 
    Double price = (Double) path.evaluate("price", product, XPathConstants.NUMBER); 
    Double quantity = (Double) path.evaluate("quantity", product, XPathConstants.NUMBER); 

    Product p = new Product(code, description, price, quantity.intValue()); 
} 
+0

給我的只是完全相同的輸出1個產品 – johnny

+0

在那裏我沒有發現一個額外的問題('count(/ inventory/products)'應該是'count(/ inventory/products/product)')。我編輯了答案並在最後添加了一個建議的改進。 – teppic

+0

完美的作品!謝謝 :) – johnny