使用java解析来自xml文件的数据

时间:2016-11-26 15:50:23

标签: java xml

所以我有这个xml文件,如下所示:

<inventory>
 <products>
  <product>
  <code>016-023</code>
  <desc>Gallon 2% Milk</desc>
  <quantity>10</quantity>
  <price>2.49</price>
 </product>
</products>
<transactions>
<purchased>
  <code>016-023</code>
  <count>5</count>
</purchased>
<sold>
  <code>019-011</code>
  <count>3</count>
 </sold>
 </transactions>
</inventory>

我需要计算所有产品并解析文件以获取要添加到新产品的代码,desc,数量和价格。我已经获得了创建对象并添加到库存部分,但无法弄清楚如何从文件中解析它。这是我到目前为止所拥有的:

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

    // Count the number of products, and then get
    // the code, desc, price, and quantity for the product
    // from the document, create a new Product object
    // from the code, desc, price, and quantity, and add the
    // product to the inventory using addProduct(). 

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


    for (Product product : products) {
        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));

        }


addProduct(new Product(code, description, price, quantity));

请帮我解决这个问题。谢谢!

0 个答案:

没有答案