XML Parsing
Document
in any way
we want.public class OrderProcessor { /** Change the value of node elemName to elemValue */ private static void changeOrder (Node start, String elemName, String elemValue) { if (start.getNodeName().equals(elemName)) { start.getFirstChild().setNodeValue(elemValue); } for (Node child = start.getFirstChild(); child != null; child = child.getNextSibling()) { changeOrder(child, elemName, elemValue); } } public static void main (String args[]) { // Change text value of node named status to processing. changeOrder(root, "status", "processing"); //Get a list of nodes that have a status element. NodeList orders = root.getElementsByTagName("status"); for (int orderNum = 0; orderNum < orders.getLength(); orderNum++) { System.out.println(orders.item(groupNum).getFirstChild().getNodeValue()); Element thisOrder = (Element)orders.item(orderNum); //Remove the limit attribute from customer. Element customer = (Element)thisOrder.getElementsByTagName("cusomertid").item(0); customer.removeAttribute("limit"); NodeList orderItems = thisOrder.getElementsByTagName("item"); double total = 0; for (int itemNum = 0; itemNum < orderItems.getLength(); itemNum++) { // Total up cost for each item and // add to the order total //Get this item as an Element Element thisOrderItem = (Element)orderItems.item(itemNum); //Remove a node. //Remove anything with <item instock="N"> if (thisOrderItem.getAttributeNode("instock").getNodeValue().equals("N")) { Node deadNode = thisOrderItem.getParentNode().removeChild(thisOrderItem); continue; //Alternatively, we could have replaced this item with a backorderd element. // <item itemid="123"> // <backordered></backordered> // </item> Element backElement = doc.createElement("backordered"); //<backordered itemid=""> backElement.setAttributeNode(doc.createAttribute("itemid")); //<backordered itemid="123"> String itemIdString = thisOrderItem.getAttributeNode("itemid").getNodeValue(); backElement.setAttribute("itemid", itemIdString); Node deadNode = thisOrderItem.getParentNode() .replaceChild(backElement, thisOrderItem); } //Get pricing information for this Item String thisPrice = thisOrderItem.getElementsByTagName("price").item(0) .getFirstChild().getNodeValue(); double thisPriceDbl = new Double(thisPrice).doubleValue(); //Get quantity information for this Item String thisQty = thisOrderItem.getElementsByTagName("qty").item(0) .getFirstChild().getNodeValue(); double thisQtyDbl = new Double(thisQty).doubleValue(); double thisItemTotal = thisPriceDbl*thisQtyDbl; total = total + thisItemTotal; } String totalString = new Double(total).toString(); //1234.34 Node totalNode = doc.createTextNode(totalString); //<total></total> Element totalElement = doc.createElement("total"); //<total>1234.34</total> totalElement.appendChild(totalNode); //Add that element before anyone else. thisOrder.insertBefore(totalElement, thisOrder.getFirstChild()); } } }
10 of 16