Plan prezentacji Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak JAXP SAX DOM STAX XSLT Akademia Górniczo - Hutnicza w Krakowie, Katedra Informatyki http://www.icsr.agh.edu.pl/~polak/ JAXB Inne interfejsy programistyczne JDOM dom4j XOM Dr inż. Stanisław Polak 1 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 2 Przedmiot: XML i jego zastosowania JAXP SAX JAXP JAXP SAX Wstęp Ang. Java API for XML Processing Parsowanie, transformacja i walidacja dokumentów XML Standardowy komponent Javy Interfejsy: SAX DOM StAX XSLT Ang. Simple API for XML Standardowy interfejs do parsowania plików XML, oparty na modelu zdarzeniowym, stworzony w celu ujednolicenia dostępu do różnych parserów XML Cechy: Model zdarzeniowy Obiektowość Prostota Sekwencyjność dostęp do danych w trakcie przetwarzania Szybkość Małe zużycie pamięci Pierwotnie zdefiniowany w języku Java Dr inż. Stanisław Polak 3 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 4 Przedmiot: XML i jego zastosowania
SAX JAXP Ilustracja działania SAX SAX JAXP SAX API 1 <? xml version=" 1.0 "?> 2 <m u l l> 3 <t e x t x="1"> 4 Przyk ł adowa zawarto ś ć 5 </ t e x t> 6 </ page> 7 <m u l l> Dokument XML SAXParser 1 startdocument ( ) 2 startelement ( ) 3 characters ( ) 4 endelement ( ) parse() Aplikacja throw SAXException Ważniejsze metody parse() startdocument() enddocument() startelement() endelement() characters() processinginstruction() error() fatalerror() warning() notationdecl() unparsedentitydecl() resolveentity() Dr inż. Stanisław Polak 5 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 6 Przedmiot: XML i jego zastosowania SAX JAXP Pakiety SAX JAXP Przetwarzanie dokumentu org.xml.sax org.xml.sax.ext org.xml.sax.helpers javax.xml.parsers 1 import java. io. ; 2 import javax. xml. parsers. ; 3 import org. xml. sax. ; 4 import org. xml. sax. helpers. ; 5 class SAX { 6 public static void main ( String [ ] args ) { 7 try { 8 SAXParserFactory fabryka = SAXParserFactory. newinstance ( ) ; 9 SAXParser parser = fabryka. newsaxparser ( ) ; 10 XMLReader czytelnik = parser. getxmlreader ( ) ; 11 czytelnik. setcontenthandler ( new MojHandler()); 12 czytelnik. parse ( new InputSource ( args [ 0 ] ) ) ; 13 } catch ( ParserConfigurationException e ) { 14 System. out. println ( e. tostring ( ) ) ; 15 } catch ( SAXException e ) { 16 System. out. println ( e. tostring ( ) ) ; 17 } catch ( IOException e ) { 18 System. out. println ( e. tostring ( ) ) ; 19 } 20 } // main ( ) 21 / / 22 private static class MojHandler extends DefaultHandler { 23 public void startdocument ( ) throws SAXException { 24 System. out. println ( "Wykryto początek dokumentu " ) ; 25 } 26 public void enddocument ( ) throws SAXException { 27 System. out. println ( "Wykryto koniec dokumentu " ) ; 29 } // MojHandler 30 } //SAX Dr inż. Stanisław Polak 7 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 8 Przedmiot: XML i jego zastosowania
SAX JAXP Obsługa walidacji DOM Wstęp 1... 2 class SAX { 3 public static void main ( String [ ] args ) { 4 try { 5... 6 fabryka. setvalidating(true) ; 7 fabryka. setnamespaceaware(true) ; 8... 9 czytelnik. seterrorhandler (MojHandlerBledow()); 10... 11 } 12.. 13 } // main ( ) 14 / / 15 private static class MojHandlerBledow implements ErrorHandler { 16 public void warning ( SAXParseException e ) throws SAXException { 17 System. out. println ( e. getmessage ( ) ) ; // gdy np. encja zosta ł a zadeklarowana kilka razy 18 } 19 20 public void error ( SAXParseException e ) throws SAXException { 21 System. out. println ( e. getmessage ( ) ) ; // gdy dokument n i e j e s t v a l i d 22 } 23 24 public void fatalerror ( SAXParseException e ) throws SAXException { 25 System. out. println ( e. getmessage ( ) ) ; //gdy dokument n i e j e s t w e l l formed 26 } 27 } // MojHandlerBledow //SAX Ang. Document Object Model Obiektowy model dostępu, strukturalizacji i nadawania stylu dokumentom Wersje: DOM Level 0 nie stanowi oficjalnego standardu W3C DOM Level 1 oficjalna rekomendacja W3C DOM Level 2 możliwość łączenia zawartości dwóch dokumentów, obsługa przestrzeni nazw DOM Level 3 obsługa XML Base, obsługa walidacji, możliwość ładowania i zachowywania dokumentów, mieszane słowniki znaczników DOM level 4 w trakcie opracowywania Cechy: Dostęp do całości dokumentu Możliwość tworzenia i modyfikacji dokumentu Duże zużycie pamięci Niska efektywność Dr inż. Stanisław Polak 9 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 10 Przedmiot: XML i jego zastosowania Reprezentacja graficzna dokumentu DOM API 1 <t a b l e> 2 <tbody> 3 <t r> 4 <td>shady Grove</ td> 5 <td>aeolian</ td> 6 </ t r> 7 <t r> 8 <td>over the River, Charlie</ td> 9 <td>dorian</ td> 10 </ t r> 11 </ tbody> 12 </ t a b l e> Ważniejsze metody newdocument() parse() Dr inż. Stanisław Polak 11 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 12 Przedmiot: XML i jego zastosowania
Pakiety Przetwarzanie istniejącego dokumentu Użycie JAXP API org.w3c.dom javax.xml.parsers 1 import javax. xml. parsers. ; 2 import org. xml. sax. ; 3 import java. io. ; 4 import org. w3c. dom. ; 5 6 public class DOM{ 7 static Document dokument ; 8 public static void main ( String argv [ ] ) { 9 DocumentBuilderFactory fabryka = DocumentBuilderFactory. newinstance ( ) ; 10 try { 11 DocumentBuilder budowniczy = fabryka. newdocumentbuilder ( ) ; 12 dokument = budowniczy. parse ( new File ( argv [ 0 ] ) ) ; 13 } catch ( ParserConfigurationException e ) { 14 e. printstacktrace ( ) ; 15 } catch ( SAXException e ) { 16 e. printstacktrace ( ) ; 17 } catch ( IOException e ) { 18 e. printstacktrace ( ) ; 19 } 20 NodeList elements = dokument. getelementsbytagname ( "tr" ) ; 21 Node tr = elements. item ( 0 ) ; 22 Node element = tr. getfirstchild ( ) ; 23 while ( element!= null ){ 24 if ( element. getnodetype ( ) == Node. ELEMENT_NODE ) 25 System. out. println ( element. getnodename ( ) ) ; // Wypisze : td 26 element = element. getnextsibling ( ) ; 27 } 29 } Dr inż. Stanisław Polak 13 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 14 Przedmiot: XML i jego zastosowania Przetwarzanie istniejącego dokumentu Użycie DOM Level 3 Load and Save Tworzenie dokumentu 1 import org. w3c. dom. bootstrap. DOMImplementationRegistry ; 2 import org. w3c. dom. ls. DOMImplementationLS ; 3 import org. w3c. dom. ls. LSParser ; 4 import org. w3c. dom. ; 5 6 public class DOM{ 7 static Document dokument ; 8 public static void main ( String argv [ ] ) { 9 try{ 10 DOMImplementationRegistry fabryka = DOMImplementationRegistry. newinstance ( ) ; 11 DOMImplementationLS impl = ( DOMImplementationLS ) fabryka. getdomimplementation ( "LS" ) ; 12 LSParser budowniczy = impl. createlsparser ( DOMImplementationLS. MODE_SYNCHRONOUS, null ) ; 13 dokument = budowniczy. parseuri ( argv [ 0 ] ) ; 14 } 15 catch ( ClassNotFoundException e ) { 16 e. printstacktrace ( ) ; 17 } 18 catch ( InstantiationException e ) { 19 e. printstacktrace ( ) ; 20 } 21 catch ( IllegalAccessException e ) { 22 e. printstacktrace ( ) ; 23 } 24 NodeList elements = dokument. getelementsbytagname ( "tr" ) ; 25 Node tr = elements. item ( 0 ) ; 26 Node element = tr. getfirstchild ( ) ; 27 while ( element!= null ){ 28 if ( element. getnodetype ( ) == Node. ELEMENT_NODE ) 29 System. out. println ( element. getnodename ( ) ) ; 30 element = element. getnextsibling ( ) ; 31 } 32 } 33 } 1 import javax. xml. parsers. ; 2 import org. w3c. dom. ; 3 public class DOMCreate{ 4 static Document dokument ; 5 public static void main ( String argv [ ] ) { 6 DocumentBuilderFactory fabryka = DocumentBuilderFactory. newinstance ( ) ; 7 try { 8 DocumentBuilder budowniczy = fabryka. newdocumentbuilder ( ) ; 9 dokument = budowniczy. newdocument ( ) ; 10 Element root = ( Element ) dokument. createelement ( " rootelement " ) ; 11 dokument. appendchild ( root ) ; 12 root. appendchild ( dokument. createtextnode ( "Some " ) ) ; 13 root. appendchild ( dokument. createtextnode ( " " ) ) ; 14 root. appendchild ( dokument. createtextnode ( "text " ) ) ; 15 } catch ( ParserConfigurationException e ) { 16 e. printstacktrace ( ) ; 17 } 18 } 19 } Dr inż. Stanisław Polak 15 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 16 Przedmiot: XML i jego zastosowania
Obsługa walidacji Serializacja dokumentu Użycie JAXP API 1... 2 class DOM { 3 public static void main ( String [ ] args ) { 4... 5 fabryka. setvalidating(true) ; 6 fabryka. setnamespaceaware(true) ; 7 try { 8... 9 budowniczy. seterrorhandler (MojHandlerBledow()); 10... 11 } 12.. 13 } // main ( ) 14 / / 15 private static class MojHandlerBledow implements ErrorHandler { 16 public void warning ( SAXParseException e ) throws SAXException { 17 System. out. println ( e. getmessage ( ) ) ; // gdy np. encja zosta ł a zadeklarowana kilka razy 18 } 19 20 public void error ( SAXParseException e ) throws SAXException { 21 System. out. println ( e. getmessage ( ) ) ; // gdy dokument n i e j e s t v a l i d 22 } 23 24 public void fatalerror ( SAXParseException e ) throws SAXException { 25 System. out. println ( e. getmessage ( ) ) ; //gdy dokument n i e j e s t w e l l formed 26 } 27 } // MojHandlerBledow //SAX 1... 2 import javax. xml. transform. ; 3 import javax. xml. transform. dom. ; 4 import javax. xml. transform. stream. 5 6 public class DOMCreate{ 7 static Document dokument ; 8 9 public static void main ( String argv [ ] ) { 10 try{ 11... 12 TransformerFactory fabryka = TransformerFactory. newinstance ( ) ; 13 Transformer transformer = fabryka. newtransformer ( ) ; 14 Source we = new DOMSource ( dokument ) ; 15 Result wy = new StreamResult ( System. out ) ; 16 transformer. transform ( we, wy ) ; 17 } catch ( ParserConfigurationException e ) { 18 e. printstacktrace ( ) ; 19 } catch ( TransformerConfigurationException e ) { 20 System. out. println ( "This DOM does not support transforms." ) ; 21 } catch ( TransformerException e ) { 22 System. out. println ( " Transform failed." ) ; 23 } 24 } 25 } Dr inż. Stanisław Polak 17 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 18 Przedmiot: XML i jego zastosowania Serializacja dokumentu Użycie DOM Level 3 Load and Save STAX JAXP STAX 1... 2 import org. w3c. dom. bootstrap. ; 3 import org. w3c. dom. ls. ; 4 5 public class DOMCreate{ 6 static Document dokument ; 7 8 public static void main ( String argv [ ] ) { 9 try{ 10... 11 DOMImplementationRegistry fabryka = DOMImplementationRegistry. newinstance ( ) ; 12 DOMImplementationLS impl = ( DOMImplementationLS ) fabryka. getdomimplementation ( "LS" ) ; 13 LSSerializer pisarz = impl. createlsserializer ( ) ; 14 String str = pisarz. writetostring ( dokument ) ; 15 System. out. println ( str ) ; 16 }catch ( ParserConfigurationException e ) { 17 e. printstacktrace ( ) ; 18 } catch ( ClassNotFoundException e ) { 19 e. printstacktrace ( ) ; 20 } catch ( InstantiationException e ) { 21 e. printstacktrace ( ) ; 22 } catch ( IllegalAccessException e ) { 23 e. printstacktrace ( ) ; 24 } 25 } 26 } Ang. Streaming API for XML API w języku Java do odczytu i zapisu dokumentów XML Dostarcza standardowego interfejsu dwukierunkowego 1 parsera strumieniowego Oferuje prostszy, w stosunku do SAX, model programistyczny oraz bardziej efektywne, w stosunku do DOM, zarządzanie pamięcią 1 odczyt / zapis dokumentu XML Dr inż. Stanisław Polak 19 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 20 Przedmiot: XML i jego zastosowania
STAX JAXP Sposoby korzystania STAX JAXP Pakiety Za pomocą kursora Interfejsy XMLStreamReader XMLStreamWriter Metody geteventtype() get... ()... Najważniejsze różnice Za pomocą zdarzeń Interfejsy XMLEventReader XMLEventWriter Metody nextevent()... Obiekty utworzone z podklas XMLEvent są niezmienne (ang. immutable) i mogą być stosowane w tablicach, listach i mapach; ponadto mogą być przekazywane za pośrednictwem aplikacji nawet jeżeli parser przeniósł się do kolejnego zdarzenia. Można dodawać i usuwać zdarzenia ze strumienia zdarzeń XML w dużo prostszy sposób niż w przypadku podejścia za pomocą kursora. javax.xml.stream javax.xml.stream.events Dr inż. Stanisław Polak 21 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 22 Przedmiot: XML i jego zastosowania STAX JAXP Przetwarzanie istniejącego dokumentu Podejście za pomocą kursora STAX JAXP Przetwarzanie istniejącego dokumentu Podejście za pomocą zdarzeń 1 import javax. xml. stream. ; 2 import java. net. URL ; 3 import java. io. ; 4 5 public class StAXRead { 6 public static void main ( String [ ] args ) { 7 String input = args [ 0 ] ; 8 try { 9 URL u = new URL ( input ) ; 10 InputStream we = u. openstream ( ) ; 11 XMLInputFactory fabryka = XMLInputFactory. newinstance ( ) ; 12 XMLStreamReader parser = fabryka. createxmlstreamreader ( we ) ; 13 for ( int zdarzenie = parser. next ( ) ; zdarzenie!= XMLStreamConstants. END_DOCUMENT ; zdarzenie = parser. next ( ) ) { 14 switch ( zdarzenie ){ 15 case XMLStreamConstants. START_ELEMENT : 16 System. out. print ( " Wykryto znacznik otwieraj ący: "+parser. getlocalname ( )+"\n" ) ; 17 break ; 18... 19 } 20 } 21 parser. close ( ) ; 22 } 23 catch ( XMLStreamException ex ) { 24 System. out. println ( ex ) ; 25 } 26 catch ( IOException ex ) { 27 System. out. println ( " IOException while parsing " + input ) ; 29 } 30 } 1 import javax. xml. stream. ; 2 import javax. xml. stream. events. ; 3 import java. io. ; 4 5 public class StAXRead { 6 public static void main ( String [ ] args ) { 7 XMLEventReader czytelnik=null ; 8 try{ 9 czytelnik = XMLInputFactory. newinstance ( ). createxmleventreader ( new java. io. FileInputStream ( args [ 0 ] ) ) ; 10 while ( czytelnik. hasnext ( ) ) { 11 XMLEvent zdarzenie = ( XMLEvent ) czytelnik. nextevent ( ) ; 12 System. out. print ( zdarzenie ) ; 13 } 14 } 15 catch ( FileNotFoundException e ) { 16 e. printstacktrace ( ) ; 17 } 18 catch ( XMLStreamException e ) { 19 e. printstacktrace ( ) ; 20 } 21 } 22 } Dr inż. Stanisław Polak 23 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 24 Przedmiot: XML i jego zastosowania
STAX JAXP Tworzenie dokumentu Podejście za pomocą kursora STAX JAXP Tworzenie dokumentu Podejście za pomocą zdarzeń 1 import javax. xml. stream. ; 2 import java. io. ; 3 4 class StAXWrite{ 5 public static void main ( String [ ] args ) { 6 try{ 7 OutputStream out = new FileOutputStream ( " data. xml " ) ; 8 XMLOutputFactory fabryka = XMLOutputFactory. newinstance ( ) ; 9 XMLStreamWriter pisarz = fabryka. createxmlstreamwriter ( out ) ; 10 pisarz. writestartdocument ( "UTF -8", "1.0 " ) ; 11 pisarz. writestartelement ( " greeting " ) ; 12 pisarz. writeattribute ( "id", "g1" ) ; 13 pisarz. writecharacters ( " Hello StAX " ) ; 14 pisarz. writeenddocument ( ) ; 15 pisarz. flush ( ) ; 16 pisarz. close ( ) ; 17 out. close ( ) ; 18 } 19 catch ( FileNotFoundException e ) { 20 e. printstacktrace ( ) ; 21 } 22 catch ( XMLStreamException e ) { 23 e. printstacktrace ( ) ; 24 } 25 catch ( IOException e ) { 26 e. printstacktrace ( ) ; 27 } 29 } //Na wyj ś ciu : <?xml version = 1.0 encoding= UTF 8?><greeting id= g1 >Hello StAX</greeting> 1 import javax. xml. stream. ; 2 import javax. xml. stream. events. ; 3 4 class StAXWrite{ 5 public static void main ( String [ ] args ) { 6 try{ 7 XMLOutputFactory fabryka = XMLOutputFactory. newinstance ( ) ; 8 XMLEventWriter pisarz = fabryka. createxmleventwriter ( System. out ) ; 9 XMLEventFactory xmleventfactory = XMLEventFactory. newinstance ( ) ; 10 StartDocument startdokument = xmleventfactory. createstartdocument ( "UTF -8", "1.0 " ) ; 11 pisarz. add ( startdokument ) ; 12 StartElement greetingse = xmleventfactory. createstartelement ( "", "", " greeting " ) ; 13 pisarz. add ( greetingse ) ; 14 Attribute atrybut = xmleventfactory. createattribute ( "id", "g1" ) ; 15 pisarz. add ( atrybut ) ; 16 Characters tekst = xmleventfactory. createcharacters ( " Hello StAx " ) ; 17 pisarz. add ( tekst ) ; 18 EndElement greetingee = xmleventfactory. createendelement ( "", "", " greeting " ) ; 19 pisarz. add ( greetingee ) ; 20 EndDocument ed = xmleventfactory. createenddocument ( ) ; 21 pisarz. add ( ed ) ; 22 pisarz. flush ( ) ; 23 pisarz. close ( ) ; 24 } 25 catch ( XMLStreamException e ) { 26 e. printstacktrace ( ) ; 27 } 29 } //Na wyj ś ciu : <?xml version = 1.0 encoding= UTF 8?><greeting id= g1 >Hello StAx</greeting> Dr inż. Stanisław Polak 25 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 26 Przedmiot: XML i jego zastosowania XSLT JAXP XSLT WE / WY XSLT JAXP XSLT API ciąg bajtów/znaków (np. plik, połączenie sieciowe), strumień zdarzeń SAX, drzewo DOM, parser strumieniowy StAX (od Java SE 6). Dr inż. Stanisław Polak 27 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 28 Przedmiot: XML i jego zastosowania
XSLT JAXP Pakiety XSLT JAXP Przekształcenie dokumentu WE na WY javax.xml.transform javax.xml.transform.dom javax.xml.transform.sax javax.xml.transform.stax javax.xml.transform.stream 1... 2 public class TransformerPlik { 3 4 public static void main ( String [ ] args ) { 5... 6 try { 7 System. out. println ( "Początek działania." ) ; 8 9 / tworzymy transformer ( z XSLT albo bez ) / 10 TransformerFactory fabryka = TransformerFactory. newinstance ( ) ; 11 Transformer transformer ; 12 if ( args. length >= 3) 13 transformer = fabryka. newtransformer ( new StreamSource ( args [ 2 ] ) ) ; 14 else 15 transformer = fabryka. newtransformer ( ) ; 16 17 / ź rod ło i cel przekszta ł cenia / 18 Source src = new StreamSource ( args [ 0 ] ) ; 19 Result res = new StreamResult ( args [ 1 ] ) ; 20 21 / i p r z e k s z t a ł camy / 22 System. out. println ( "Początek przekształcania." ) ; 23 transformer. transform ( src, res ) ; 24 System. out. println ( "Koniec przekształcania." ) ; 25 } catch ( Exception e ) { 26 System. out. println ( e. getmessage ( ) ) ; 27 e. printstacktrace ( ) ; 29 } 30 } Dr inż. Stanisław Polak 29 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 30 Przedmiot: XML i jego zastosowania JAXB JAXB Charakterystyka JAXB Architektura Ang. Java Architecture for XML Binding Realizuje ideę wiązania XML w Javie Mapowanie hierarchii klas na schemat dokumentu XML Wchodzi w skład JavaEE oraz JAVA SE 1.6 Dr inż. Stanisław Polak 31 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 32 Przedmiot: XML i jego zastosowania
JAXB Przykład Hello World JAXB Proces wiązania Plik XML Schema 1. Generowanie klas 2. Kompilowanie klas 3. Odczyt danych (Unmarshal) 4. Generowanie drzewa zawartości 5. Walidacja (opcjonalna) 6. Przetwarzanie zawartości 7. Zapis danych XML (Marshal) 1 <? xml version=" 1.0 " e n c o d i n g="utf -8"?> 2 <xsd:schema x m l n s : x s d=" http: // www.w3.org /2001/ XMLSchema " 3 x m l n s : j x b=" http: // java.sun.com /xml /ns/jaxb " 4 j x b : v e r s i o n=" 2.0 "> 5 6 <x s d : e l e m e n t name=" Greetings " t y p e=" GreetingListType "/> 7 8 <xsd:complextype name=" GreetingListType "> 9 <x s d : s e q u e n c e> 10 <x s d : e l e m e n t name=" Greeting " t y p e=" GreetingType " 11 maxoccurs=" unbounded "/> 12 </ x s d : s e q u e n c e> 13 </ xsd:complextype> 14 15 <xsd:complextype name=" GreetingType "> 16 <x s d : s e q u e n c e> 17 <x s d : e l e m e n t name="text " t y p e=" xsd:string "/> 18 </ x s d : s e q u e n c e> 19 <x s d : a t t r i b u t e name=" language " t y p e=" xsd:language "/> 20 </ xsd:complextype> 21 22 </ xsd:schema> 1 $ xjc p hello hello. xsd 2 parsing a schema... 3 compiling a schema... 4 hello / GreetingListType. java 5 hello / GreetingType. java 6 hello / ObjectFactory. java Kompilacja schematu hello.xsd Dr inż. Stanisław Polak 33 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 34 Przedmiot: XML i jego zastosowania Przykład Hello World JAXB Wygenerowane pliki Plik GreetingType.java Przykład Hello World JAXB Wygenerowane pliki Plik GreetingListType.java 1 package hello ; 2... 3 public class GreetingType { 4 @XmlElement ( name = "Text ", required = true ) 5 protected String text ; 6 @XmlAttribute ( name = " language " ) 7 @XmlJavaTypeAdapter ( CollapsedStringAdapter. class ) 8 @XmlSchemaType ( name = " language " ) 9 protected String language ; 10 11 public String gettext ( ) { 12 return text ; 13 } 14 15 public void settext ( String value ) { 16 this. text = value ; 17 } 18 19 public String getlanguage ( ) { 20 return language ; 21 } 22 23 public void setlanguage ( String value ) { 24 this. language = value ; 25 } 26 } 1 package hello ; 2... 3 public class GreetingListType { 4 @XmlElement ( name = " Greeting ", required = true ) 5 protected List<GreetingType> greeting ; 6 7 public List<GreetingType> getgreeting ( ) { 8 if ( greeting == null ) { 9 greeting = new ArrayList<GreetingType >() ; 10 } 11 return this. greeting ; 12 } 13 } Dr inż. Stanisław Polak 35 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 36 Przedmiot: XML i jego zastosowania
Przykład Hello World JAXB Wygenerowane pliki Plik ObjectFactory.java 1 package hello ; 2... 3 public class ObjectFactory { 4 5 private final static QName _Greetings_QNAME = new QName ( "", " Greetings " ) ; 6 7 public ObjectFactory ( ) { 8 } 9 10 public GreetingListType creategreetinglisttype ( ) { 11 return new GreetingListType ( ) ; 12 } 13 14 public GreetingType creategreetingtype ( ) { 15 return new GreetingType ( ) ; 16 } 17 18 @XmlElementDecl ( namespace = "", name = " Greetings " ) 19 public JAXBElement<GreetingListType> creategreetings ( GreetingListType value ) { 20 return new JAXBElement<GreetingListType >(_Greetings_QNAME, GreetingListType. class, null, value ) ; 21 } 22 } Dr inż. Stanisław Polak 37 Przedmiot: XML i jego zastosowania Przykład Hello World JAXB Przykład użycia Plik Hello.java 1 import java. util. ; 2 import javax. xml. bind. ; 3 import hello. ; 4 5 public class Hello { 6 private ObjectFactory of ; 7 private GreetingListType grlist ; 8 9 public static void main( String argv [ ] ) { 10 Hello h = new Hello ( ) ; 11 h. make ( " Bonjour, madame ", "fr" ) ; 12 h. make ( "Hey, you ", "en" ) ; 13 h. marshal ( ) ; 14 } 15 public Hello ( ){ 16 of = new ObjectFactory ( ) ; 17 grlist = of. creategreetinglisttype ( ) ; 18 } 19 20 public void make( String t, String l ){ 21 GreetingType g = of. creategreetingtype ( ) ; 22 g. settext ( t ) ; 23 g. setlanguage ( l ) ; 24 grlist. getgreeting ( ). add ( g ) ; 25 } 26 27 public void marshal ( ) { 28 try { 29 JAXBElement<GreetingListType> gl = of. creategreetings ( grlist ) ; 30 JAXBContext jc = JAXBContext. newinstance ( " hello " ) ; 31 Marshaller m = jc. createmarshaller ( ) ; 32 m. marshal ( gl, System. out ) ; 33 } catch ( JAXBException jbe ) {... } 34 } 35 } Dr inż. Stanisław Polak 38 Przedmiot: XML i jego zastosowania Przykład Hello World JAXB Dokument wynikowy JDOM Inne interfejsy programistyczne JDOM Ogólna charakterystyka 1 <? xml version=" 1.0 " e n c o d i n g="utf -8" standalone=" yes "?> 2 <G r e e t i n g s> 3 <G r e e t i n g l a n g u a g e="fr"> 4 <Text>Bonjour, madame</ Text> 5 </ G r e e t i n g> 6 <G r e e t i n g l a n g u a g e="en"> 7 <Text>Hey, you</ Text> 8 </ G r e e t i n g> 9 </ G r e e t i n g s> hello.xml API oparte na drzewie, przeznaczone tylko do obsługi XML i tylko w języku Java. Inaczej niż w DOM, węzły drzewa są reprezentowane jako konkretne klasy, a nie interfejsy Nie zawiera własnego parsera Obiekt DOM Document można konwertować w obiekt Document w JDOM Dane dla drzewa mogą pochodzić ze źródeł nie-xml Drzewo JDOM można modyfikować Możliwość serializacji drzewa Dr inż. Stanisław Polak 39 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 40 Przedmiot: XML i jego zastosowania
JDOM Inne interfejsy programistyczne Tworzenie dokumentu 1 import org. jdom2. ; 2 import org. jdom2. input. ; 3 import org. jdom2. output. ; 4 import java. io. ; 5 6 public class JDOM { 7 public static void main ( String [ ] args ) { 8 Element message = new Element ( " message " ) ; 9 message. setattribute ( " type ", " normal " ) ; 10 message. addcontent ( new Text ( " Hello World!" ) ) ; 11 Element root = new Element ( "root " ) ; 12 root. addcontent ( message ) ; 13 Document doc = new Document ( root ) ; 14 XMLOutputter xout = new 15 XMLOutputter ( Format. getprettyformat ( ) ) ; 16 try{ 17 xout. output ( doc, System. out ) ; 18 } 19 catch ( IOException e ){} 20 } 21 } dom4j Inne interfejsy programistyczne dom4j Ogólna charakterystyka Biblioteka do pracy z XML, XPath oraz XSLT Mniejszy i szybszy w stosunku do JDOM Węzły reprezentowane przez interfejsy Java Możliwość tworzenia dokumentu na podstawie zdarzeń SAX lub drzewa DOM i zapisywania go w postaci zdarzeń SAX lub drzewa DOM Na wyjściu <?xml version="1.0" encoding="utf-8"?> <root> <message type="normal">hello World!</message> </root> Dr inż. Stanisław Polak 41 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 42 Przedmiot: XML i jego zastosowania dom4j Inne interfejsy programistyczne XOM Inne interfejsy programistyczne Tworzenie dokumentu 1 import org. dom4j. Document ; 2 import org. dom4j. DocumentHelper ; 3 import org. dom4j. Element ; 4 import org. dom4j. io. OutputFormat ; 5 import org. dom4j. io. XMLWriter ; 6 import java. io. ; 7 8 public class DOM4J { 9 10 public Document createdocument ( ) { 11 Document document = DocumentHelper. createdocument ( ) ; 12 Element root = document. addelement ( " root " ) ; 13 Element message = root. addelement ( " message " ) 14. addattribute ( " type ", " normal " ) 15. addtext ( " Hello World!" ) ; 16 return document ; 17 } 18 19 public static void main ( String [ ] args ) { 20 DOM4J dom4j = new DOM4J ( ) ; 21 Document document = dom4j. createdocument ( ) ; 22 OutputFormat format = OutputFormat. createprettyprint ( ) ; 23 try{ 24 XMLWriter writer = new XMLWriter ( System. out, format ) ; 25 writer. write ( document ) ; 26 } 27 catch ( IOException e ){} 29 } Drzewiasta reprezentacja dokumentu XML Koncepcje zapożyczone z JDOM Używa parsera SAX do stworzenia drzewa... Funkcjonalności, które nie występują w JDOM Obsługa XInclude Lepsze wsparcie dla dokumentów nieprawidłowych, w tym walidacja bez odrzucenia nieprawidłowych dokumentów i zgłaszanie więcej niż jednego błędu walidacji na dokument... Dr inż. Stanisław Polak 43 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 44 Przedmiot: XML i jego zastosowania
XOM Inne interfejsy programistyczne Źródła Tworzenie dokumentu Źródła I 1 import nu. xom. ; 2 3 public class XOM { 4 5 public static void main ( String [ ] args ) { 6 7 Element root = new Element ( "root " ) ; 8 Element message = new Element ( " message " ) ; 9 Attribute type = new Attribute ( "type ", " normal " ) ; 10 message. addattribute ( type ) ; 11 message. appendchild ( " Hello World!" ) ; 12 root. appendchild ( message ) ; 13 Document doc = new Document ( root ) ; 14 String result = doc. toxml ( ) ; 15 System. out. println ( result ) ; 16 } 17 } Patryk Czarnik. XML i nowoczesne technologie zarządzania treścią. http://www.mimuw.edu.pl/~czarnik/. Elliotte Rusty Harold. An Introduction to StAX. http://www.xml.com/pub/a/2003/09/17/stax.html. Elliotte Rusty Harold. XOM Tutorial. http://www.xom.nu/tutorial.xhtml. Jason Hunter, i in. JDOM 2.0. https://github.com/hunterhacker/jdom/wiki/jdom-2.0. Wolfgang Laun. A JAXB Tutorial. https://jaxb.dev.java.net/tutorial/. Dr inż. Stanisław Polak 45 Przedmiot: XML i jego zastosowania Dr inż. Stanisław Polak 46 Przedmiot: XML i jego zastosowania Źródła Źródła II MetaStuff Ltd. DOM4j Quick start. http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html. Oracle Sun. The Java Web Services Tutorial. http://java.sun.com/webservices/docs/2.0/tutorial/doc/. Inc. Sun Microsystems. Java API for XML Processing (JAXP) Tutorial. http://java.sun.com/webservices/reference/tutorials/jaxp/ html/intro.html. W3C. Document Object Model (DOM) Level 3 Core Specification. http://www.w3.org/tr/2004/rec-dom-level-3-core-20040407/. Dr inż. Stanisław Polak 47 Przedmiot: XML i jego zastosowania