Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Java and XML Modified from presentation by: Barry Burd Drew University Portions © 2002 Hungry Minds, Inc.

Similar presentations


Presentation on theme: "1 Java and XML Modified from presentation by: Barry Burd Drew University Portions © 2002 Hungry Minds, Inc."— Presentation transcript:

1 1 Java and XML Modified from presentation by: Barry Burd Drew University me@BarryBurd.com Portions © 2002 Hungry Minds, Inc.

2 2 Outline Review of XML Discussion of some Java XML APIs includingDiscussion of some Java XML APIs –SAX –DOM

3 3 Review of XML Hello Start tag End tag Processing instruction Characters (text)

4 4 Review of XML <?xml version="1.0" encod Hello Element Attribute name Attribute value

5 5 Review of XML... Empty Elements Entity references

6 6 Document Type Definition (DTD) <!ATTLIST note pitch CDATA #REQUIRED>...Etc.

7 7 A Doc that’s not well-formed Hello world! How are you? <!-- Oh, no! This start tag should be an end tag! --> Comment

8 8 An Invalid Document Hello world! <!-- No Question element in the DTD --> How are you?

9 9 A valid document Hello world! How are you?

10 10 Outline Review of XML Discussion of some Java XML APIs –What APIs are availableWhat APIs are available –SAXSAX –DOMDOM –Validation, namespaces, etc.Validation, namespaces, etc. –Creating a new XML document using DOMCreating a new XML document using DOM –Using XSLUsing XSL

11 11 Some of the Java APIs JAXP (Java API for XML Processing) –SAX (Simple API for XML) –DOM (Document Object Model) –JAXP comes standard with J2SE 1.4 –It is installed on cerebro if you use the path /usr/local/linux-jdk1.3.1/bin

12 12 SAX Event driven Deals with start tags, end tags, etc. No inherent notion of an element No inherent notion of nesting No in-memory copy of the whole document

13 13 import javax.xml.parsers.*; import org.xml.sax.*; import java.io.*; class CallSAX { static public void main(String[] args) throws SAXException, ParserConfigurationException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler (new MyContentHandler()); //...(more) Calling SAX

14 14 import javax.xml.parsers.*; import org.xml.sax.*; import java.io.*; class CallSAX { static public void main(String[] args) throws SAXException, ParserConfigurationException, IOException { //...Stuff from previous slide xmlReader.parse (new File(“weather.xml"). toURL().toString()); } Calling SAX

15 15 A Content Handler import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.Attributes; class MyContentHandler extends DefaultHandler { public void startDocument() { System.out.println ("Starting the document."); } // More...

16 16 A Content Handler (cont’d) public void startElement(String uri, String localName, String qualName, Attributes attribs) { System.out.print("Start tag: "); System.out.println(qualName); for (int i=0; i<attribs.getLength(); i++) { System.out.print("Attribute: "); System.out.print(attribs.getQName(i)); System.out.print(" = "); System.out.println(attribs.getValue(i)); }

17 17 A Content Handler (cont’d) public void characters (char[] charArray, int start, int length) { String charString = new String(charArray, start, length); charString = charString.replaceAll("\n", "[cr]"); charString = charString.replaceAll(" ", "[blank]"); System.out.print(length + " characters: "); System.out.println(charString); }

18 18 A Content Handler (cont’d) public void endElement(String uri, String localName, String qualName) { System.out.print("End tag: "); System.out.println(qualName); } public void endDocument() { System.out.println("Ending the document."); }

19 19 A Sample Document White Plains NY Sat Jul 25 1998 11 am EDT 70 82 62

20 20 The Output Starting the document. Start tag: WeatherReport 1 characters: $ Start tag: City 12 characters: White Plains End tag: City 1 characters: $ Start tag: State 2 characters: NY End tag: State 1 characters: $ Start tag: Date 15 characters: Sat Jul 25 1998 End tag: Date 1 characters: $ Start tag: Time 9 characters: 11 am EDT End tag: Time 1 characters: $ Start tag: CurrTemp Attribute: unit = Farenheit 2 characters: 70 End tag: CurrTemp 1 characters: $ Start tag: High Attribute: unit = Farenheit 2 characters: 82 End tag: High 1 characters: $ Start tag: Low Attribute: unit = Farenheit 2 characters: 62 End tag: Low 1 characters: $ End tag: WeatherReport Ending the document.

21 21 DOM Not event driven Creates an in-memory copy of the document Deals with document nodes Nodes are nested Elements are nodes, but so are attributes, text, processing instructions, comments, the entire document itself No inherent notion of a tag

22 22 Calling DOM import javax.xml.parsers.*; import org.xml.sax.SAXException; import java.io.*; import org.w3c.dom.Document; public class CallDOM { public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc; // More... }

23 23 Calling DOM import javax.xml.parsers.*; import org.xml.sax.SAXException; import java.io.*; import org.w3c.dom.Document; public class CallDOM { public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException { //... Stuff from previous slide if (args.length == 1) { doc = builder.parse (new File(args[0]).toURL().toString()); new MyTreeTraverser (doc); } else System.out.println ("Usage: java CallDOM file-name.xml"); }

24 24 class MyTreeTraverser { String indent=""; MyTreeTraverser (Node node) { traverse(node); } void traverse(Node node){ displayName(node); displayValue(node); if (node.getNodeType() == Node.ELEMENT_NODE) displayAttributes(node); indent=indent.concat(" "); displayChildren(node); indent=indent.substring(0,indent.length()-3); } // …stuff void displayChildren(Node node) { Node child = node.getFirstChild(); while (child != null) { traverse(child); child = child.getNextSibling(); } A Tree Traverser

25 25 The Output Name: #document Value: null Name: WeatherReport Value: null Name: #text Value: Name: City Value: null Name: #text Value: White Plains Name: #text Value: Name: State Value: null Name: #text Value: NY Name: #text Value: Name: Date Value: null Name: #text Value: Sat Jul 25 1998 Name: #text Value: Name: Time Value: null Name: #text Value: 11 am EDT Name: #text Value: Name: CurrTemp Value: null Attribute: Unit = Farenheit Name: #text Value: 70 Name: #text Value: Name: High Value: null Attribute: Unit = Farenheit Name: #text Value: 82 Name: #text Value: Name: Low Value: null Attribute: Unit = Farenheit Name: #text Value: 62 Name: #text Value:

26 26 Setting an Error Handler In SAX: xmlReader.setErrorHandler new MyErrorHandler()); In DOM builder.setErrorHandler (new MyErrorHandler());

27 27 An Error Handler import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.SAXParseException; class MyErrorHandler extends DefaultHandler { public void error(SAXParseException e) { System.out.println("Error:"); showSpecifics(e); System.out.println(); } public void showSpecifics(SAXParseException e) { System.out.println(e.getMessage()); System.out.println (" Line " + e.getLineNumber()); System.out.println (" Column " + e.getColumnNumber()); System.out.println (" Document " + e.getSystemId()); }

28 28 import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.SAXParseException; class MyErrorHandler extends DefaultHandler { public void warning(SAXParseException e) { System.out.println("Warning:"); showSpecifics(e); System.out.println(); } public void fatalError(SAXParseException e) { System.out.println("Fatal error:"); showSpecifics(e); System.out.println(); } //... } An Error Handler (cont’d)

29 29 Turning on DTD Validation // must do this before using the factory factory.setValidating(true);

30 30 The Output Error: Attribute value for "Unit" is #REQUIRED. Line 9 Column -1 Document file:/usr/local/www/data/csci380/02s/examples/xml/DOMvalid/weather2.xml Name: #document Value: null Name: WeatherReport Value: null Name: WeatherReport Value: null …

31 31 About This Book Conventions Used in This Book A "Hello" Example Doing Validation A "Hello" Example Creating a new document Using XSL

32 32 <xsl:stylesheet xmlns:xsl= http://www.w3.org/1999/XSL/Transform version="1.0"> Part <xsl:value-of select="@number"/>: <xsl:value-of select="@title"/> An XSL Stylesheet

33 33     <xsl:if test="@number">Chapter <xsl:value-of select="@number"/>: <xsl:value-of select="@title"/> #160;       •     Appendix <xsl:value-of select="@number"/>: <xsl:value-of select="@title"/> An XSL Stylesheet (cont’d)

34 34 JavaAndXMLforDummies.htm Java and XML For Dummies Introduction • About This Book • Conventions Used in This Book Part I: The Big Picture Chapter 1: SAX... Etc.

35 35 Java and XML For Dummies Introduction About This Book Conventions Used in This Book Part I: The Big Picture Chapter 1: SAX A "Hello" Example Doing Validation Chapter 2: DOM A "Hello" Example Creating a new document Appendixes Appendix A: Things to Remember about Java Appendix B: Things to Remember about XML

36 36 Applying XSL with Java Code import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; More...

37 37 Applying XSL with Java Code (cont’d) public class MyTransform { public static void main(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer (new StreamSource("JavaAndXMLforDummies.xsl")); transformer.transform (new StreamSource("JavaAndXMLforDummies.xml"), new StreamResult (new FileOutputStream("JavaAndXMLforDummies.htm"))); }

38 38 The Usual Scenario... Client Browser http GET request for JavaAndXMLforDummies.jsp HTTP server Servlet container.xml file.xsl file.jsp file.htm file response


Download ppt "1 Java and XML Modified from presentation by: Barry Burd Drew University Portions © 2002 Hungry Minds, Inc."

Similar presentations


Ads by Google