SlideShare uma empresa Scribd logo
1 de 21
Simple API for XML (SAX) XML http://yht4ever.blogspot.com [email_address] B070066 - NIIT Quang Trung 08/2007
Contents Events SAX-based Parsers DOM vs. SAX Introduction
Introduction ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DOM vs. SAX ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
SAX-based Parsers ,[object Object],[object Object],[object Object]
SAX-based Parsers ,[object Object],[object Object],[object Object]
Example: Tree Diagram 1 // Fig. 9.3 : Tree.java 2 // Using the SAX Parser to generate a tree diagram. 3 4 import  java.io.*; 5 import  org.xml.sax.*;  // for HandlerBase class 6 import  javax.xml.parsers.SAXParserFactory; 7 import  javax.xml.parsers.ParserConfigurationException; 8 import  javax.xml.parsers.SAXParser; 9 10 public class  Tree  extends  HandlerBase { 11   private int  indent = 0;  // indentation counter 12 13   // returns the spaces needed for indenting 14   private  String spacer(  int  count ) 15   { 16   String temp = &quot;&quot;; 17 18   for  (  int  i = 0; i < count; i++ ) 19   temp += &quot;  &quot;; 20 21   return  temp; 22   } 23 24   // method called before parsing 25   // it provides the document location 26   public void  setDocumentLocator( Locator loc ) 27   { 28   System.out.println( &quot;URL: &quot; + loc.getSystemId() ); 29   } 30 1 // Fig. 9.3 : Tree.java 2 // Using the SAX Parser to generate a tree diagram. 3 4 import  java.io.*; 5 import  org.xml.sax.*;  // for HandlerBase class 6 import  javax.xml.parsers.SAXParserFactory; 7 import  javax.xml.parsers.ParserConfigurationException; 8 import  javax.xml.parsers.SAXParser; 9 10 public class  Tree  extends  HandlerBase { 11   private int  indent = 0;  // indentation counter 12 13   // returns the spaces needed for indenting 14   private  String spacer(  int  count ) 15   { 16   String temp = &quot;&quot;; 17 18   for  (  int  i = 0; i < count; i++ ) 19   temp += &quot;  &quot;; 20 21   return  temp; 22   } 23 24   // method called before parsing 25   // it provides the document location 26   public void  setDocumentLocator( Locator loc ) 27   { 28   System.out.println( &quot;URL: &quot; + loc.getSystemId() ); 29   } 30 import  specifies location of classes needed by application Assists in formatting Override method to output parsed document’s URL
31   // method called at the beginning of a document 32   public void  startDocument()  throws  SAXException 33   { 34   System.out.println( &quot;[ document root ]&quot; ); 35   } 36 37   // method called at the end of the document 38   public void  endDocument()  throws  SAXException 39   { 40   System.out.println( &quot;[ document end ]&quot; ); 41   } 42 43   // method called at the start tag of an element 44   public void  startElement( String name, 45   AttributeList attributes )  throws  SAXException 46   { 47   System.out.println( spacer( indent++ ) + 48   &quot;+-[ element : &quot; + name + &quot; ]&quot;); 49 50   if  ( attributes !=  null  ) 51 52   for  (  int  i = 0; i < attributes.getLength(); i++ ) 53   System.out.println( spacer( indent ) + 54   &quot;+-[ attribute : &quot; + attributes.getName( i ) + 55   &quot; ] amp;quot;&quot; + attributes.getValue( i ) + &quot;amp;quot;&quot; ); 56   } 57 Overridden method called when root node encountered Overridden method called when end of document is encountered Overridden method called when start tag is encountered Output each attribute’s name and value (if any)
58   // method called at the end tag of an element 59   public void  endElement( String name )  throws  SAXException 60   { 61   indent--; 62   } 63 64   // method called when a processing instruction is found 65   public void  processingInstruction( String target, 66   String value )  throws  SAXException 67   { 68   System.out.println( spacer( indent ) + 69   &quot;+-[ proc-inst : &quot; + target + &quot; ] amp;quot;&quot; + value + &quot;amp;quot;&quot; ); 70   } 71 72   // method called when characters are found 73   public void  characters(  char  buffer[],  int  offset, 74   int  length )  throws  SAXException 75   { 76   if  ( length > 0 ) { 77   String temp =  new  String( buffer, offset, length ); 78 79   System.out.println( spacer( indent ) + 80   &quot;+-[ text ] amp;quot;&quot; + temp + &quot;amp;quot;&quot; ); 81   } 82   } 83 Overridden method called when end of element is encountered Overridden method called when processing instruction is encountered Overridden method called when character data is encountered
84   // method called when ignorable whitespace is found 85   public void  ignorableWhitespace(  char  buffer[], 86   int  offset,  int  length ) 87   { 88   if  ( length > 0 ) { 89   System.out.println( spacer( indent ) + &quot;+-[ ignorable ]&quot; ); 90   } 91   } 92 93   // method called on a non-fatal (validation) error 94   public void  error( SAXParseException spe )  95   throws  SAXParseException 96   { 97   // treat non-fatal errors as fatal errors 98   throw  spe; 99   } 100 101   // method called on a parsing warning 102   public void  warning( SAXParseException spe ) 103   throws  SAXParseException 104   { 105   System.err.println( &quot;Warning: &quot; + spe.getMessage() ); 106   } 107 108   // main method 109   public static void   main( String args[] ) 110   { 111   boolean  validate =  false ; 112 Overridden method called when ignorable whitespace is encountered Overridden method called when error (usually validation) occurs Overridden method called when problem is detected (but not considered error) Method  main  starts application
113   if  ( args.length != 2 ) { 114   System.err.println( &quot;Usage: java Tree [validate] &quot; + 115   &quot;[filename]&quot; ); 116   System.err.println( &quot;Options:&quot; ); 117   System.err.println( &quot;  validate [yes|no] : &quot; + 118   &quot;DTD validation&quot; ); 119   System.exit( 1 ); 120   } 121 122   if  ( args[ 0 ].equals( &quot;yes&quot; ) ) 123   validate =  true ; 124 125   SAXParserFactory saxFactory = 126   SAXParserFactory.newInstance(); 127 128   saxFactory.setValidating( validate ); 129 Allow command-line arguments (if we want to validate document) SAXParserFactory  can instantiate SAX-based parser
130   try  { 131   SAXParser saxParser = saxFactory.newSAXParser(); 132   saxParser.parse(  new  File( args[ 1 ] ),  new  Tree() ); 133   } 134   catch  ( SAXParseException spe ) { 135   System.err.println( &quot;Parse Error: &quot; + spe.getMessage() ); 136   } 137   catch  ( SAXException se ) { 138   se.printStackTrace(); 139   } 140   catch  ( ParserConfigurationException pce ) { 141   pce.printStackTrace(); 142   } 143   catch  ( IOException ioe ) { 144   ioe.printStackTrace(); 145   } 146 147   System.exit( 0 ); 148   } 149 } Instantiate SAX-based parser Handles errors (if any)
URL: file:C:/Tree/spacing1.xml [ document root ] +-[ element : test ]   +-[ attribute : name ] &quot;  spacing 1  &quot;   +-[ text ] &quot; &quot;   +-[ text ] &quot;  &quot;   +-[ element : example ]   +-[ element : object ]   +-[ text ] &quot;World&quot;   +-[ text ] &quot; &quot; [ document end ]   1 <?xml version =  &quot;1.0&quot; ?> 2 3 <!-- Fig. 9.4 : spacing1.xml  --> 4 <!-- Whitespaces in nonvalidating parsing --> 5 <!-- XML document without DTD  --> 6 7 <test name =  &quot;  spacing 1  &quot; > 8   <example><object> World </object></example> 9 </test> Root element  test  contains attribute  name  with value  “ spacing 1 ” XML document with elements  test ,  example  and  object XML document does not reference DTD Note that whitespace is preserved: attribute value (line 7), line feed (end of line 7), indentation (line 8) and line feed (end of line 8)
URL: file:C:/Tree/spacing2.xml [ document root ] +-[ element : test ]   +-[ attribute : name ] &quot;  spacing 2  &quot;   +-[ ignorable ]   +-[ ignorable ]   +-[ element : example ]   +-[ element : object ]   +-[ text ] &quot;World&quot;   +-[ ignorable ] [ document end ]   1 <?xml version =  &quot;1.0&quot; ?> 2 3 <!-- Fig. 9.5 : spacing2.xml  --> 4 <!-- Whitespace and nonvalidated parsing --> 5 <!-- XML document with DTD  --> 6 7 <!DOCTYPE  test  [ 8 <!ELEMENT  test (example) > 9 <!ATTLIST  test name  CDATA #IMPLIED> 10 <!ELEMENT  element (object*) > 11 <!ELEMENT  object   ( #PCDATA ) > 12 ]> 13 14 <test name =  &quot;  spacing 2  &quot; > 15   <example><object> World </object></example> 16 </test> DTD checks document’s characters, so any “removable” whitespace is ignorable Line feed at line 14, spaces at beginning of line 15 and line feed at line 15 are ignored
URL: file:C:/Tree/notvalid.xml [ document root ] +-[ element : test ]   +-[ ignorable ]   +-[ ignorable ]   +-[ proc-inst : test ] &quot;message&quot;   +-[ ignorable ]   +-[ ignorable ]   +-[ element : example ]   +-[ element : item ]   +-[ text ] &quot;Hello & Welcome!&quot;   +-[ ignorable ] [ document end ]   1 <?xml version =  &quot;1.0&quot; ?> 2 3 <!-- Fig. 9.6 : notvalid.xml  --> 4 <!-- Validation and non-validation --> 5 6 <!DOCTYPE  test  [ 7 <!ELEMENT  test (example) > 8 <!ELEMENT  example ( #PCDATA ) > 9 ]> 10 11 <test> 12   <?test message?> 13   <example><item><![CDATA[ Hello & Welcome! ]]></item></example> 14 </test> Invalid document because element  example  cannot contain element  item Validation disabled, so document parses successfully Parser does not process text in  CDATA  section and returns character data
URL: file:C:/Tree/notvalid.xml [ document root ] +-[ element : test ]   +-[ ignorable ]   +-[ ignorable ]   +-[ proc-inst : test ] &quot;message&quot;   +-[ ignorable ]   +-[ ignorable ]   +-[ element : example ] Parse Error: Element &quot;example&quot; does not allow &quot;item&quot; Parsing terminates when fatal error occurs at element  item Validation enabled
URL: file:C:/Tree/valid.xml [ document root ] +-[ element : test ]   +-[ text ] &quot; &quot;   +-[ text ] &quot;  &quot;   +-[ element : example ]   +-[ text ] &quot;Hello &quot;   +-[ text ] &quot;&&quot;   +-[ text ] &quot; Welcome!&quot;   +-[ text ] &quot; &quot; [ document end ]   URL: file:C:/Tree/valid.xml [ document root ] Warning: Valid documents must have a <!DOCTYPE declaration. Parse Error: Element type &quot;test&quot; is not declared.   1 <?xml version =  &quot;1.0&quot; ?> 2 3 <!-- Fig. 9.7 : valid.xml  --> 4 <!-- DTD-less document  --> 5 6 <test> 7   <example> Hello &amp; Welcome! </example> 8 </test> Validation disabled in first output, so document parses successfully Validation enabled in second output, and parsing fails because DTD does not exist
To be continued… ,[object Object]
Reference ,[object Object],[object Object]
Q&A ,[object Object],[object Object]
http://yht4ever.blogspot.com Thank You !

Mais conteúdo relacionado

Mais procurados

Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6Fiyaz Hasan
 
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅재춘 노
 
merged_document_3
merged_document_3merged_document_3
merged_document_3tori hoff
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestHoward Lewis Ship
 
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...Mumbai B.Sc.IT Study
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginnersishan0019
 
The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210Mahmoud Samir Fayed
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicNew Relic
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180Mahmoud Samir Fayed
 
Advanced Dynamic Analysis for Leak Detection (Apple Internship 2008)
Advanced Dynamic Analysis for Leak Detection (Apple Internship 2008)Advanced Dynamic Analysis for Leak Detection (Apple Internship 2008)
Advanced Dynamic Analysis for Leak Detection (Apple Internship 2008)James Clause
 

Mais procurados (20)

Tugas 2
Tugas 2Tugas 2
Tugas 2
 
14 thread
14 thread14 thread
14 thread
 
Base de-datos
Base de-datosBase de-datos
Base de-datos
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Lab4
Lab4Lab4
Lab4
 
Java practical
Java practicalJava practical
Java practical
 
merged_document_3
merged_document_3merged_document_3
merged_document_3
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To Test
 
Network
NetworkNetwork
Network
 
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180
 
2 презентация rx java+android
2 презентация rx java+android2 презентация rx java+android
2 презентация rx java+android
 
Advanced Dynamic Analysis for Leak Detection (Apple Internship 2008)
Advanced Dynamic Analysis for Leak Detection (Apple Internship 2008)Advanced Dynamic Analysis for Leak Detection (Apple Internship 2008)
Advanced Dynamic Analysis for Leak Detection (Apple Internship 2008)
 

Destaque

Java Web Service - Summer 2004
Java Web Service - Summer 2004Java Web Service - Summer 2004
Java Web Service - Summer 2004Danny Teng
 
Jaxp Xmltutorial 11 200108
Jaxp Xmltutorial 11 200108Jaxp Xmltutorial 11 200108
Jaxp Xmltutorial 11 200108nit Allahabad
 
Java Web Services [2/5]: Introduction to SOAP
Java Web Services [2/5]: Introduction to SOAPJava Web Services [2/5]: Introduction to SOAP
Java Web Services [2/5]: Introduction to SOAPIMC Institute
 
Java Web Services [5/5]: REST and JAX-RS
Java Web Services [5/5]: REST and JAX-RSJava Web Services [5/5]: REST and JAX-RS
Java Web Services [5/5]: REST and JAX-RSIMC Institute
 
Xml Java
Xml JavaXml Java
Xml Javacbee48
 
Java Web Services [3/5]: WSDL, WADL and UDDI
Java Web Services [3/5]: WSDL, WADL and UDDIJava Web Services [3/5]: WSDL, WADL and UDDI
Java Web Services [3/5]: WSDL, WADL and UDDIIMC Institute
 
java API for XML DOM
java API for XML DOMjava API for XML DOM
java API for XML DOMSurinder Kaur
 
Java Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web ServicesJava Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web ServicesIMC Institute
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7Lukáš Fryč
 
Java Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web ServicesJava Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web ServicesIMC Institute
 
Community and Java EE @ DevConf.CZ
Community and Java EE @ DevConf.CZCommunity and Java EE @ DevConf.CZ
Community and Java EE @ DevConf.CZMarkus Eisele
 
Writing simple web services in java using eclipse editor
Writing simple web services in java using eclipse editorWriting simple web services in java using eclipse editor
Writing simple web services in java using eclipse editorSantosh Kumar Kar
 

Destaque (20)

6 xml parsing
6   xml parsing6   xml parsing
6 xml parsing
 
Java XML Parsing
Java XML ParsingJava XML Parsing
Java XML Parsing
 
Xml processors
Xml processorsXml processors
Xml processors
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
XML DOM
XML DOMXML DOM
XML DOM
 
JAXP
JAXPJAXP
JAXP
 
Java Web Service - Summer 2004
Java Web Service - Summer 2004Java Web Service - Summer 2004
Java Web Service - Summer 2004
 
Jaxp Xmltutorial 11 200108
Jaxp Xmltutorial 11 200108Jaxp Xmltutorial 11 200108
Jaxp Xmltutorial 11 200108
 
Java Web Services [2/5]: Introduction to SOAP
Java Web Services [2/5]: Introduction to SOAPJava Web Services [2/5]: Introduction to SOAP
Java Web Services [2/5]: Introduction to SOAP
 
Java Web Services [5/5]: REST and JAX-RS
Java Web Services [5/5]: REST and JAX-RSJava Web Services [5/5]: REST and JAX-RS
Java Web Services [5/5]: REST and JAX-RS
 
Xml Java
Xml JavaXml Java
Xml Java
 
Java Web Services [3/5]: WSDL, WADL and UDDI
Java Web Services [3/5]: WSDL, WADL and UDDIJava Web Services [3/5]: WSDL, WADL and UDDI
Java Web Services [3/5]: WSDL, WADL and UDDI
 
java API for XML DOM
java API for XML DOMjava API for XML DOM
java API for XML DOM
 
Java Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web ServicesJava Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web Services
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Java Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web ServicesJava Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web Services
 
Community and Java EE @ DevConf.CZ
Community and Java EE @ DevConf.CZCommunity and Java EE @ DevConf.CZ
Community and Java EE @ DevConf.CZ
 
Writing simple web services in java using eclipse editor
Writing simple web services in java using eclipse editorWriting simple web services in java using eclipse editor
Writing simple web services in java using eclipse editor
 
Dom parser
Dom parserDom parser
Dom parser
 

Semelhante a Simple API for XML

Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaJevgeni Kabanov
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
Dynamic Tracing of your AMP web site
Dynamic Tracing of your AMP web siteDynamic Tracing of your AMP web site
Dynamic Tracing of your AMP web siteSriram Natarajan
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...zznate
 
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxInstruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxcarliotwaycave
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2wiradikusuma
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageabilityDaniel Fisher
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Appium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionAppium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionpCloudy
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web PerformanceAdam Lu
 

Semelhante a Simple API for XML (20)

Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
 
Jsp And Jdbc
Jsp And JdbcJsp And Jdbc
Jsp And Jdbc
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Dynamic Tracing of your AMP web site
Dynamic Tracing of your AMP web siteDynamic Tracing of your AMP web site
Dynamic Tracing of your AMP web site
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
Hector v2: The Second Version of the Popular High-Level Java Client for Apach...
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
srgoc
srgocsrgoc
srgoc
 
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxInstruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
 
Xm lparsers
Xm lparsersXm lparsers
Xm lparsers
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Appium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionAppium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation Execution
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
 
Apache Cassandra and Go
Apache Cassandra and GoApache Cassandra and Go
Apache Cassandra and Go
 

Último

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 

Último (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 

Simple API for XML

  • 1. Simple API for XML (SAX) XML http://yht4ever.blogspot.com [email_address] B070066 - NIIT Quang Trung 08/2007
  • 2. Contents Events SAX-based Parsers DOM vs. SAX Introduction
  • 3.
  • 4.
  • 5.
  • 6.
  • 7. Example: Tree Diagram 1 // Fig. 9.3 : Tree.java 2 // Using the SAX Parser to generate a tree diagram. 3 4 import java.io.*; 5 import org.xml.sax.*; // for HandlerBase class 6 import javax.xml.parsers.SAXParserFactory; 7 import javax.xml.parsers.ParserConfigurationException; 8 import javax.xml.parsers.SAXParser; 9 10 public class Tree extends HandlerBase { 11 private int indent = 0; // indentation counter 12 13 // returns the spaces needed for indenting 14 private String spacer( int count ) 15 { 16 String temp = &quot;&quot;; 17 18 for ( int i = 0; i < count; i++ ) 19 temp += &quot; &quot;; 20 21 return temp; 22 } 23 24 // method called before parsing 25 // it provides the document location 26 public void setDocumentLocator( Locator loc ) 27 { 28 System.out.println( &quot;URL: &quot; + loc.getSystemId() ); 29 } 30 1 // Fig. 9.3 : Tree.java 2 // Using the SAX Parser to generate a tree diagram. 3 4 import java.io.*; 5 import org.xml.sax.*; // for HandlerBase class 6 import javax.xml.parsers.SAXParserFactory; 7 import javax.xml.parsers.ParserConfigurationException; 8 import javax.xml.parsers.SAXParser; 9 10 public class Tree extends HandlerBase { 11 private int indent = 0; // indentation counter 12 13 // returns the spaces needed for indenting 14 private String spacer( int count ) 15 { 16 String temp = &quot;&quot;; 17 18 for ( int i = 0; i < count; i++ ) 19 temp += &quot; &quot;; 20 21 return temp; 22 } 23 24 // method called before parsing 25 // it provides the document location 26 public void setDocumentLocator( Locator loc ) 27 { 28 System.out.println( &quot;URL: &quot; + loc.getSystemId() ); 29 } 30 import specifies location of classes needed by application Assists in formatting Override method to output parsed document’s URL
  • 8. 31 // method called at the beginning of a document 32 public void startDocument() throws SAXException 33 { 34 System.out.println( &quot;[ document root ]&quot; ); 35 } 36 37 // method called at the end of the document 38 public void endDocument() throws SAXException 39 { 40 System.out.println( &quot;[ document end ]&quot; ); 41 } 42 43 // method called at the start tag of an element 44 public void startElement( String name, 45 AttributeList attributes ) throws SAXException 46 { 47 System.out.println( spacer( indent++ ) + 48 &quot;+-[ element : &quot; + name + &quot; ]&quot;); 49 50 if ( attributes != null ) 51 52 for ( int i = 0; i < attributes.getLength(); i++ ) 53 System.out.println( spacer( indent ) + 54 &quot;+-[ attribute : &quot; + attributes.getName( i ) + 55 &quot; ] amp;quot;&quot; + attributes.getValue( i ) + &quot;amp;quot;&quot; ); 56 } 57 Overridden method called when root node encountered Overridden method called when end of document is encountered Overridden method called when start tag is encountered Output each attribute’s name and value (if any)
  • 9. 58 // method called at the end tag of an element 59 public void endElement( String name ) throws SAXException 60 { 61 indent--; 62 } 63 64 // method called when a processing instruction is found 65 public void processingInstruction( String target, 66 String value ) throws SAXException 67 { 68 System.out.println( spacer( indent ) + 69 &quot;+-[ proc-inst : &quot; + target + &quot; ] amp;quot;&quot; + value + &quot;amp;quot;&quot; ); 70 } 71 72 // method called when characters are found 73 public void characters( char buffer[], int offset, 74 int length ) throws SAXException 75 { 76 if ( length > 0 ) { 77 String temp = new String( buffer, offset, length ); 78 79 System.out.println( spacer( indent ) + 80 &quot;+-[ text ] amp;quot;&quot; + temp + &quot;amp;quot;&quot; ); 81 } 82 } 83 Overridden method called when end of element is encountered Overridden method called when processing instruction is encountered Overridden method called when character data is encountered
  • 10. 84 // method called when ignorable whitespace is found 85 public void ignorableWhitespace( char buffer[], 86 int offset, int length ) 87 { 88 if ( length > 0 ) { 89 System.out.println( spacer( indent ) + &quot;+-[ ignorable ]&quot; ); 90 } 91 } 92 93 // method called on a non-fatal (validation) error 94 public void error( SAXParseException spe ) 95 throws SAXParseException 96 { 97 // treat non-fatal errors as fatal errors 98 throw spe; 99 } 100 101 // method called on a parsing warning 102 public void warning( SAXParseException spe ) 103 throws SAXParseException 104 { 105 System.err.println( &quot;Warning: &quot; + spe.getMessage() ); 106 } 107 108 // main method 109 public static void main( String args[] ) 110 { 111 boolean validate = false ; 112 Overridden method called when ignorable whitespace is encountered Overridden method called when error (usually validation) occurs Overridden method called when problem is detected (but not considered error) Method main starts application
  • 11. 113 if ( args.length != 2 ) { 114 System.err.println( &quot;Usage: java Tree [validate] &quot; + 115 &quot;[filename]&quot; ); 116 System.err.println( &quot;Options:&quot; ); 117 System.err.println( &quot; validate [yes|no] : &quot; + 118 &quot;DTD validation&quot; ); 119 System.exit( 1 ); 120 } 121 122 if ( args[ 0 ].equals( &quot;yes&quot; ) ) 123 validate = true ; 124 125 SAXParserFactory saxFactory = 126 SAXParserFactory.newInstance(); 127 128 saxFactory.setValidating( validate ); 129 Allow command-line arguments (if we want to validate document) SAXParserFactory can instantiate SAX-based parser
  • 12. 130 try { 131 SAXParser saxParser = saxFactory.newSAXParser(); 132 saxParser.parse( new File( args[ 1 ] ), new Tree() ); 133 } 134 catch ( SAXParseException spe ) { 135 System.err.println( &quot;Parse Error: &quot; + spe.getMessage() ); 136 } 137 catch ( SAXException se ) { 138 se.printStackTrace(); 139 } 140 catch ( ParserConfigurationException pce ) { 141 pce.printStackTrace(); 142 } 143 catch ( IOException ioe ) { 144 ioe.printStackTrace(); 145 } 146 147 System.exit( 0 ); 148 } 149 } Instantiate SAX-based parser Handles errors (if any)
  • 13. URL: file:C:/Tree/spacing1.xml [ document root ] +-[ element : test ] +-[ attribute : name ] &quot; spacing 1 &quot; +-[ text ] &quot; &quot; +-[ text ] &quot; &quot; +-[ element : example ] +-[ element : object ] +-[ text ] &quot;World&quot; +-[ text ] &quot; &quot; [ document end ] 1 <?xml version = &quot;1.0&quot; ?> 2 3 <!-- Fig. 9.4 : spacing1.xml --> 4 <!-- Whitespaces in nonvalidating parsing --> 5 <!-- XML document without DTD --> 6 7 <test name = &quot; spacing 1 &quot; > 8 <example><object> World </object></example> 9 </test> Root element test contains attribute name with value “ spacing 1 ” XML document with elements test , example and object XML document does not reference DTD Note that whitespace is preserved: attribute value (line 7), line feed (end of line 7), indentation (line 8) and line feed (end of line 8)
  • 14. URL: file:C:/Tree/spacing2.xml [ document root ] +-[ element : test ] +-[ attribute : name ] &quot; spacing 2 &quot; +-[ ignorable ] +-[ ignorable ] +-[ element : example ] +-[ element : object ] +-[ text ] &quot;World&quot; +-[ ignorable ] [ document end ] 1 <?xml version = &quot;1.0&quot; ?> 2 3 <!-- Fig. 9.5 : spacing2.xml --> 4 <!-- Whitespace and nonvalidated parsing --> 5 <!-- XML document with DTD --> 6 7 <!DOCTYPE test [ 8 <!ELEMENT test (example) > 9 <!ATTLIST test name CDATA #IMPLIED> 10 <!ELEMENT element (object*) > 11 <!ELEMENT object ( #PCDATA ) > 12 ]> 13 14 <test name = &quot; spacing 2 &quot; > 15 <example><object> World </object></example> 16 </test> DTD checks document’s characters, so any “removable” whitespace is ignorable Line feed at line 14, spaces at beginning of line 15 and line feed at line 15 are ignored
  • 15. URL: file:C:/Tree/notvalid.xml [ document root ] +-[ element : test ] +-[ ignorable ] +-[ ignorable ] +-[ proc-inst : test ] &quot;message&quot; +-[ ignorable ] +-[ ignorable ] +-[ element : example ] +-[ element : item ] +-[ text ] &quot;Hello & Welcome!&quot; +-[ ignorable ] [ document end ] 1 <?xml version = &quot;1.0&quot; ?> 2 3 <!-- Fig. 9.6 : notvalid.xml --> 4 <!-- Validation and non-validation --> 5 6 <!DOCTYPE test [ 7 <!ELEMENT test (example) > 8 <!ELEMENT example ( #PCDATA ) > 9 ]> 10 11 <test> 12 <?test message?> 13 <example><item><![CDATA[ Hello & Welcome! ]]></item></example> 14 </test> Invalid document because element example cannot contain element item Validation disabled, so document parses successfully Parser does not process text in CDATA section and returns character data
  • 16. URL: file:C:/Tree/notvalid.xml [ document root ] +-[ element : test ] +-[ ignorable ] +-[ ignorable ] +-[ proc-inst : test ] &quot;message&quot; +-[ ignorable ] +-[ ignorable ] +-[ element : example ] Parse Error: Element &quot;example&quot; does not allow &quot;item&quot; Parsing terminates when fatal error occurs at element item Validation enabled
  • 17. URL: file:C:/Tree/valid.xml [ document root ] +-[ element : test ] +-[ text ] &quot; &quot; +-[ text ] &quot; &quot; +-[ element : example ] +-[ text ] &quot;Hello &quot; +-[ text ] &quot;&&quot; +-[ text ] &quot; Welcome!&quot; +-[ text ] &quot; &quot; [ document end ] URL: file:C:/Tree/valid.xml [ document root ] Warning: Valid documents must have a <!DOCTYPE declaration. Parse Error: Element type &quot;test&quot; is not declared. 1 <?xml version = &quot;1.0&quot; ?> 2 3 <!-- Fig. 9.7 : valid.xml --> 4 <!-- DTD-less document --> 5 6 <test> 7 <example> Hello &amp; Welcome! </example> 8 </test> Validation disabled in first output, so document parses successfully Validation enabled in second output, and parsing fails because DTD does not exist
  • 18.
  • 19.
  • 20.