johnny johnny - 12 days ago 5
Java Question

parse xml not cycling?

I need to parse an .xml file that has numerous amounts of products, and I need it to return all the products found int he .xml file.

However, the code I have only returns one of these products and doesn't touch the other products even though they are in the .xml file.

Here's my code, can someone help me figure this out?

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);

}

}
}


Thanks!

Answer

Firstly, you're counting the number of products elements, not product elements. This is always 1. The correct count is

"count(/inventory/products/product)" 

You'll also need to place the index on the child element, not the parent.

For example

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

not

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

You can simplify this significantly by working directly with the product nodes:

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());
}