1 import net.sf.saxon.jdom.DocumentWrapper; 2 import net.sf.saxon.xpath.XPathEvaluator; 3 import net.sf.saxon.Configuration; 4 import org.jdom.Document; 5 import org.jdom.Element; 6 import org.jdom.JDOMException; 7 import org.jdom.input.SAXBuilder; 8 9 import javax.xml.transform.*; 10 import javax.xml.transform.stream.StreamResult; 11 import javax.xml.transform.stream.StreamSource; 12 import java.io.File; 13 import java.io.IOException; 14 import java.util.Iterator; 15 16 22 public class JDOMExample { 23 24 private JDOMExample() {} 25 26 29 public static void main(String argv[]) 30 throws TransformerException, TransformerConfigurationException, 31 JDOMException, IOException { 32 33 if (argv.length == 2) { 34 transform(argv[0], argv[1]); 35 } else { 36 System.err.println("Usage: JDOMExample source.xml style.xsl >out.xml"); 37 } 38 39 } 40 41 45 46 public static void transform(String sourceID, String xslID) 47 throws TransformerException, TransformerConfigurationException, 48 JDOMException, IOException { 49 50 51 SAXBuilder builder = new SAXBuilder(); 53 Document doc = builder.build(new File(sourceID)); 54 55 DocumentWrapper docw = new DocumentWrapper(doc, sourceID, new Configuration()); 57 58 XPathEvaluator xpath = new XPathEvaluator(docw); 60 Iterator iter = xpath.evaluate("//ITEM").iterator(); 61 62 64 while (iter.hasNext()) { 65 Element item = (Element)iter.next(); 68 String price = item.getChildText("PRICE"); 69 String quantity = item.getChildText("QUANTITY"); 70 try { 71 double priceval = Double.parseDouble(price); 72 double quantityval = Double.parseDouble(quantity); 73 double value = priceval * quantityval; 74 item.setAttribute("VALUE", ""+value); 75 } catch (NumberFormatException err) { 76 item.setAttribute("VALUE", "?"); 77 } 78 } 79 80 82 System.setProperty("javax.xml.transform.TransformerFactory", 83 "net.sf.saxon.TransformerFactoryImpl"); 84 TransformerFactory tfactory = TransformerFactory.newInstance(); 85 86 90 Templates templates = tfactory.newTemplates(new StreamSource(xslID)); 91 Transformer transformer = templates.newTransformer(); 92 93 transformer.transform(docw, new StreamResult(System.out)); 94 95 } 96 97 98 } 99 | Popular Tags |