-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個產品 – johnny
在那裏我沒有發現一個額外的問題('count(/ inventory/products)'應該是'count(/ inventory/products/product)')。我編輯了答案並在最後添加了一個建議的改進。 – teppic
完美的作品!謝謝 :) – johnny