/Users/lyon/j4p/src/xml/ModifXmlPrices.java

1    /** 
2     *  ModifXmlPrices.java 
3     * @author Thomas Rowland 
4     * @version 02-08-03 
5     */ 
6     
7    package xml; 
8     
9    import futils.Futil; 
10   import org.w3c.dom.*; 
11   import org.xml.sax.ErrorHandler; 
12   import org.xml.sax.SAXException; 
13   import org.xml.sax.SAXParseException; 
14    
15   import javax.xml.parsers.DocumentBuilder; 
16   import javax.xml.parsers.DocumentBuilderFactory; 
17   import javax.xml.parsers.ParserConfigurationException; 
18   import java.io.*; 
19    
20   // for SAX exceptions 
21    
22    
23   /* 
24    * DomParser program for Product.xml. 
25    * This program parses the XML file, increases 
26    * the <UnitPrice> element values for each <Product>, and 
27    * writes the modified XML out to a new file "NewProduct.xml". 
28    * This program uses the DOM Level 2 api and JAXP 1.2. 
29    */ 
30    
31   public class ModifXmlPrices { 
32       // Node type constants 
33       static final int ELEMENT_NODE = 1; 
34       static final int TEXT_NODE = 3; 
35       static final int DOCUMENT_NODE = 9; 
36    
37       static float incr = 0; 
38       static BufferedWriter out = null; 
39    
40       public static void main(String[] args) 
41               throws IOException { 
42           System.out.println("Enter percent price increase: "); 
43           BufferedReader in = new BufferedReader( 
44                   new InputStreamReader(System.in)); 
45           incr = new Float(in.readLine()).floatValue() * .01f; 
46    
47           File inFile = Futil.getReadFile("select an XML file"); 
48           File outFile = new File(inFile.getParent() + "\\NewProduct.xml"); 
49           out = new BufferedWriter(new FileWriter(outFile)); 
50    
51           parse("file:" + inFile.getAbsolutePath()); 
52           out.flush(); 
53           out.close(); 
54       } 
55    
56    
57       /** 
58        *  Parses an xml file 
59        */ 
60       private static void parse(String uri) 
61               throws IOException { 
62    
63           // First get the factory 
64           DocumentBuilderFactory dbf = 
65                   DocumentBuilderFactory.newInstance(); 
66           try { 
67               //dbf.setValidating(true); 
68    
69               // Get the DocumentBuilder 
70               DocumentBuilder db = dbf.newDocumentBuilder(); 
71    
72               // Set an error handler 
73               db.setErrorHandler(new MyErrorHandler()); 
74    
75               // Parse the file and get back a DOM Document 
76               Document doc = db.parse(uri); 
77    
78               // Get the root element from the DOM Document 
79               Element root = doc.getDocumentElement(); 
80    
81               // Now we can traverse the Document and print out results 
82               traverse(root); 
83               printNode(doc); 
84           } catch (ParserConfigurationException e) { 
85               // Factory unable to create parser. 
86               System.out.println( 
87                       "** ParserConfigurationException\n" 
88                       + e.getMessage()); 
89           } catch (SAXException e) { 
90               // Parsing error. 
91               System.out.println( 
92                       "** SAXException\n" 
93                       + e.getMessage()); 
94               // Get wrapped exception 
95               Exception ex = e.getException(); 
96               if (ex != null) 
97                   ex.printStackTrace(); 
98           } catch (IOException e) { 
99               e.printStackTrace(); 
100          } 
101      } 
102   
103   
104      /** 
105       * Recursive method which traverses an Element 
106       * and searches for the <UnitPrice> element. 
107       */ 
108      private static void traverse(Node elem) { 
109          try { 
110              if (elem.hasChildNodes()) { 
111                  NodeList children = elem.getChildNodes(); 
112                  int length = children.getLength(); 
113   
114                  for (int i = 0; i < length; i++) { 
115                      Node n = children.item(i); 
116                      String name = n.getNodeName(); 
117   
118                      if (n.getNodeType() == ELEMENT_NODE) { 
119                          traverse(n);    //recurse 
120                      } else if (n.getNodeType() == TEXT_NODE) { 
121                          String pname = n.getParentNode().getNodeName(); 
122                          if (pname.equals("UnitPrice")) { 
123                              String price = n.getNodeValue(); 
124                              System.out.println(pname + " = " + price); 
125                              float f = (new Float(price).floatValue()) * (1 + incr); 
126                              int newPrice = new Float(f).intValue(); 
127   
128                              n.setNodeValue(String.valueOf(newPrice)); 
129                              System.out.println("new value of " + pname + 
130                                      " = " + n.getNodeValue() + "\n"); 
131                              return; 
132                          } 
133                      } 
134                  } 
135                  return; 
136              } 
137          } catch (DOMException e) { 
138              System.out.println("*** DOMException\n" 
139                      + e.getMessage()); 
140          } 
141      } 
142   
143   
144      /* 
145       * Recursive method which prints out a DOM element 
146       */ 
147      private static void printNode(Node node) 
148              throws IOException { 
149          switch (node.getNodeType()) { 
150              case Node.DOCUMENT_NODE: 
151                  out.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"" 
152                          + "standalone=\"yes\"?>\n\n"); 
153   
154                  Document doc = (Document) node; 
155   
156                  out.write("<!DOCTYPE " 
157                          + doc.getDocumentElement().getNodeName() 
158                          + " [" + doc.getDoctype().getInternalSubset() 
159                          + "]>\n"); 
160   
161  // recurse on each child 
162                  NodeList nodes = node.getChildNodes(); 
163                  if (nodes != null) { 
164                      for (int i = 0; i < nodes.getLength(); i++) { 
165                          printNode(nodes.item(i)); 
166                      } 
167                  } 
168                  break; 
169   
170              case Node.ELEMENT_NODE: 
171                  String name = node.getNodeName(); 
172                  out.write("<" + name); 
173                  NamedNodeMap attributes = node.getAttributes(); 
174                  for (int i = 0; i < attributes.getLength(); i++) { 
175                      Node attr = attributes.item(i); 
176                      out.write(" " + attr.getNodeName() + 
177                              "=\"" + attr.getNodeValue() + 
178                              "\""); 
179                      out.newLine(); 
180                  } 
181   
182                  out.write(">"); 
183   
184  // recurse on each child 
185                  NodeList children = node.getChildNodes(); 
186   
187                  if (children != null) { 
188                      for (int i = 0; i < children.getLength(); i++) 
189                          printNode(children.item(i)); 
190                  } 
191   
192                  out.write("</" + name + ">"); 
193   
194              case Node.TEXT_NODE: 
195                  String val = node.getNodeValue(); 
196                  if (val != null) 
197                      out.write(val); 
198                  break; 
199          } 
200      } 
201   
202   
203      /* 
204       * Error Handler to report validation errors and warnings. 
205       */ 
206      private static class MyErrorHandler implements ErrorHandler { 
207   
208          /* 
209           * Returns a string describing parse exception details 
210           */ 
211          private String getParseExceptionInfo(SAXParseException spe) { 
212              String systemId = spe.getSystemId(); 
213              if (systemId == null) { 
214                  systemId = "null"; 
215              } 
216              String info = "URI=" + systemId + 
217                      "\nLine=" + spe.getLineNumber() + 
218                      "\n" + spe.getMessage(); 
219              return info; 
220          } 
221   
222          /* 
223           * The following methods are standard SAX ErrorHandler 
224           * methods used by DOM 
225           */ 
226          public void warning(SAXParseException spe) throws SAXException { 
227              System.out.println("Warning: " + getParseExceptionInfo(spe)); 
228          } 
229   
230          public void error(SAXParseException spe) throws SAXException { 
231              String message = "Error: " + getParseExceptionInfo(spe); 
232              throw new SAXException(message); 
233          } 
234   
235          public void fatalError(SAXParseException spe) throws SAXException { 
236              String message = "Fatal Error: " + getParseExceptionInfo(spe); 
237              throw new SAXException(message); 
238          } 
239      }// 
240   
241  }//