HI,
Im relatively new to XML and was wondering how I could use DOM to produce a "per shop" report showing a list of the items available in the given shop (shop 1 first then 2), the item description, stock level and calculate a total value of the stock level from the xml code below? I want to use the shop id as an input to the program. How can I get to the shop element and from there choose the item child?


<shops>
<shop number="1">
<address>
<street>Rigby Lane</street>
<town>Houghton</town>
</address>

<items>

<item number="11">
<itemname>Black Coat</itemname>
<description>long coat</description>
<price>15.99</price>
<stocklevel>12</stocklevel>
</item>

<item number="12">
<itemname>Jumper</itemname>
<description>DKNY wool</description>
<price>40.99</price>
<stocklevel>7</stocklevel>
</item>

<item number="13">
<itemname>Gloves</itemname>
<description>blue gloves</description>
<price>0.99</price>
<stocklevel>23</stocklevel>
</item>
</items>
</shop>

<shop number="2">

<address>
<street>Polaris Road</street>
<town>High Wikem</town>
</address>

<items>
<item number="14">
<itemname>Boots</itemname>
<description>Ankle</description>
<price>35.00</price>
<stocklevel>2</stocklevel>
</item>

<item number="15">
<itemname>Tights</itemname>
<description>denier 60</description>
<price>5.49</price>
<stocklevel>19</stocklevel>
</item>

</items>
</shop>
</shops>

Dani AI

Generated

The easiest approach is: parse the file into a DOM, use an XPath like /shops/shop[@number='N'] to find the shop node for the requested id, then iterate that shop's items/item nodes, read itemname, description, price and stocklevel, compute price * stocklevel for each item and accumulate a BigDecimal total (avoid double/float for currency). This answers the original question from ; the later replies by , , , and are moderation chatter and do not affect the technical solution.

Steps

  1. Build a DOM (DocumentBuilder).
  2. Use XPath to select the shop node: /shops/shop[@number='X'].
  3. From that shop, select items/item and for each item extract text content.
  4. Convert price to BigDecimal and stocklevel to int, compute line total and add to a running BigDecimal total.
  5. Format totals for display.

Example (Java, DOM + XPath):

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;

public class ShopReport {
  public static void main(String[] args) throws Exception {
    String shopId = args.length>0 ? args[0] : "1";
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("shops.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node shop = (Node) xpath.evaluate("/shops/shop[@number='" + shopId + "']", doc, XPathConstants.NODE);
    if (shop==null) { System.out.println("Shop not found: " + shopId); return; }
    NodeList items = (NodeList) xpath.evaluate("items/item", shop, XPathConstants.NODESET);
    BigDecimal total = BigDecimal.ZERO;
    DecimalFormat df = new DecimalFormat("#0.00");
    for (int i=0;i<items.getLength();i++){
      Element it = (Element) items.item(i);
      String name = xpath.evaluate("itemname", it).trim();
      String desc = xpath.evaluate("description", it).trim();
      BigDecimal price = new BigDecimal(xpath.evaluate("price", it).trim());
      int stock = Integer.parseInt(xpath.evaluate("stocklevel", it).trim());
      BigDecimal line = price.multiply(new BigDecimal(stock));
      total = total.add(line);
      System.out.printf("%s - %s - %d @ %s = %s%n", name, desc, stock, df.format(price), df.format(line));
    }
    System.out.println("TOTAL: " + df.format(total));
  }
}

Troubleshooting and tips

  • Use new BigDecimal(string) (not double) to avoid rounding errors.
  • trim() values; handle missing nodes with null checks.
  • If XML is very large, switch from DOM to a streaming parser (SAX/StAX).
  • For a presentable report consider XSLT to transform XML directly to HTML or CSV.

Recommended Answers

All 6 Replies

Hi

I don't know if this is an old post or not. pice23 has been spamming my PM box, and this above post is also spam. do something, someone.

I also got PM spam from him (And reported it)

pice23 has now been officially warned about the PM spam stuff...

excus me but can you please ban that guy or something as he keeps spamming my pm over and over and I'm getting pissed off.

pice23 has now been officially warned about the PM spam stuff...

Thats very nice ... Most sites if someone Spams someone via PM they are banned straight away... (I hope he doesnt do it anymore)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.