pczapiewski.zut.edu.pl

Download Report

Transcript pczapiewski.zut.edu.pl

Piotr Czapiewski
Wydział Informatyki ZUT

Extensible Markup Language
 Język znaczników
 Human-readable and machine-readable
 Niezależny od platformy
 Reprezentacja dokumentów lub danych
ustrukturalizowanych



Deklaracja XML
Element główny (root)
Elementy



Zagnieżdżanie
Atrybuty
Elementy puste
<?xml version="1.0" encoding="UTF-8"?>
<katalog>
<ksiazka id="1001">
<tytul>Java i XML. Wydanie III</tytul>
<autorzy>
<autor>Brett D. McLaughlin</autor>
<autor>Justin Edelson</autor>
</autorzy>
<wydawnictwo>Helion</wydawnictwo>
<rok>2007</rok>
<strony n="440" />
</ksiazka>
</katalog>

Metajęzyk
 Brak zdefiniowanych
znaczników, jedynie reguły
znakowania

XML
XHTML
Aplikacje XML
 Specjalizowane języki
bazujące na XML
 XHTML, WML, SVG, MathML,
DocBook, WSDL, …
DTD
XHTML
Definiowanie struktury
dokumentu XML
DTD
XML Schema
<!DOCTYPE kontakty [
<?xml version="1.0" ?>
<kontakty>
<!ELEMENT kontakty (kontakt+)>
<!ELEMENT kontakt (imie, nazwisko,
email*, telefon*, uwagi?)>
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
imie (#PCDATA)>
nazwisko (#PCDATA)>
email (#PCDATA)>
telefon (#PCDATA)>
<!ATTLIST kontakt
typ (prywatny | służbowy)
"prywatny"
id ID #REQUIRED>
<!ATTLIST telefon
typ (stacjonarny | komórkowy)
"stacjonarny">
]>
<kontakt typ="prywatny" id="a01">
<imie>Piotr</imie>
<nazwisko>Czapiewski</nazwisko>
<email>[email protected]</email>
<email>[email protected]</email>
<telefon>123456789</telefon>
</kontakt>
<kontakt typ="służbowy" id="a02">
<imie>Jan</imie>
<nazwisko>Kowalski</nazwisko>
<email>[email protected]</email>
<telefon typ="stacjonarny">
1234567</telefon>
<telefon typ="komórkowy">
66665432</telefon>
</kontakt>
</kontakty>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://wi.zut.edu.pl/ia/books"
xmlns="http://wi.zut.edu.pl/ia/books"
elementFormDefault="qualified">
<xs:complexType name="book">
<xs:sequence>
<xs:element name="title"
type="xs:string" />
<xs:element name="author"
type="xs:string" />
<xs:element name="isbn"
type="xs:string" />
<xs:element name="publisher"
type="xs:string" />
<xs:element name="year"
type="xs:int" />
<xs:element name="pages"
type="xs:int" />
</xs:sequence>
<xs:attribute name="id" type="xs:string" use="required"/>
</xs:complexType>
<xs:complexType name="books">
<xs:sequence>
<xs:element name="book" type="book" minOccurs="1" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:element name="books" type="books" />
</xs:schema>
<xs:element name="books" type="books" />
<xs:complexType name="books">
<xs:sequence>
<xs:element name="book"
type="book"
minOccurs="1"
maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="book">
...
...
</xs:complexType>
<?xml version="1.0" ?>
<books>
<book id="a001">
<title>Java i XML</tytul>
<authors>
<author>B. McLaughlin</author>
<author>J. Edelson</author>
</authors>
<publisher>Helion</publisher>
<year>2007</year>
<pages>440</pages>
</book>
<book id="xb07">
...
</book>
</books>
<xs:complexType name="book">
<xs:sequence>
<xs:element name="title"
type="xs:string"
<xs:element name="author"
type="xs:string"
<xs:element name="isbn"
type="xs:string"
<xs:element name="publisher"
type="xs:string"
<xs:element name="year"
type="xs:int" />
<xs:element name="pages"
type="xs:int" />
</xs:sequence>
<xs:attribute name="id"
type="xs:string"
use="required"/>
</xs:complexType>
<?xml version="1.0" ?>
<books>
/>
/>
/>
/>
<book id="a001">
<title>Java i XML</tytul>
<authors>
<author>B. McLaughlin</author>
<author>J. Edelson</author>
</authors>
<publisher>Helion</publisher>
<year>2007</year>
<pages>440</pages>
</book>
<book id="xb07">
...
</book>
</books>



Zapobieganie konfliktom nazw
Elementy z różnych „słowników” w jednym dokumencie
Deklaracja: prefiks oraz URI
<root xmlns:h="http://www.w3.org/TR/html4/">
<h:table>
<h:tr>
<h:td>Product</h:td>
<h:td>Description</h:td>
</h:tr>
</h:table>
</root>
<table>
<tr>
<td>Product</td>
<td>Description</td>
</tr>
</table>
<table>
<name>Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
<root
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Product</h:td>
<h:td>Description</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
Parsowanie
• DOM, SAX
Wiązanie XML
• JAXB
Przeszukiwanie
• XPath
Przekształcenia
• XSLT
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="100E27">
<title>100 sposobów na Excel 2007 PL</title>
<author>David Hawley, Raina Hawley</author>
<isbn>978-83-246-1331-1</isbn>
<publisher>Helion</publisher>
<year>2008</year>
<pages>368</pages>
</book>
<book id="100EBI">
<title>125 pytań na temat e-biznesu do Piotra Majewskiego</title>
<author>Piotr Majewski</author>
<isbn>978-83-246-2723-3</isbn>
<publisher>Helion</publisher>
<year>2010</year>
<pages>224</pages>
</book>
</books>

SAX – Simple API for XML
 Parsowanie sekwencyjne
 Sterowane zdarzeniami

Zdarzenia w SAX
 Generowane, gdy parser napotka w dokumencie:
▪ znacznik otwierający lub zamykający,
▪ węzeł tekstowy,
▪ instrukcję przetwarzania,
▪ komentarz.

Handler SAX
 Klasa obsługująca zdarzenia
▪ definiowana przez użytkownika,
▪ wywoływana przez parser SAX.
private static class MyHandler extends DefaultHandler {
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
...
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
...
}
public void characters(char[] ch, int start, int length)
throws SAXException {
...
}
};
private static class MyHandler extends DefaultHandler {
private int bookCount = 0;
private List<String> titles = new ArrayList<String>();
private boolean book = false;
private boolean title = false;
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
...
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
...
}
public void characters(char[] ch, int start, int length)
throws SAXException {
...
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(qName.equals("book")) {
bookCount++;
book = true;
} else if(qName.equals("title")) {
title = true;
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(qName.equals("book"))
book = false;
else if(qName.equals("title"))
title = false;
}
public void characters(char[] ch, int start, int length) throws SAXException {
if(book && title) {
String title = new String(ch, start, length);
titles.add(title);
}
}
SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
MyHandler handler = new MyHandler();
sax.parse("books3.xml", handler);
int bookCount = handler.getBookCount();
List<String> titles = handler.getTitles();
System.out.println(bookCount);
System.out.println(titles);

DOM – Document Object Model
 Model obiektowy reprezentujący dokument XML
 Standard W3C DOM – zbiór klas i interfejsów
operujących na węzłach w dokumencie
 Dokument reprezentowany w pamięci jako
drzewo węzłów

Rodzaje węzłów w DOM
 element,
 atrybut,
 tekst,
 komentarz,
 i kilka innych…
<?xml version="1.0" ?>
<books>
<book id="a001">
<title>Java i XML</tytul>
<authors>
<author>B. McLaughlin</author>
<author>J. Edelson</author>
</authors>
<publisher>Helion</publisher>
<year>2007</year>
<pages>440</pages>
</book>
<book id="xb07">
...
</book>
</books>
Document
Root
(books)
Element
(book)
Attribute
(id)
Element
(title)
Text
Element
(book)
Element
(authors)
…
Element
(author)
Element
(author)
Text
Text
…
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse("books3.xml");
Element root = doc.getDocumentElement();
String rootName = root.getNodeName();
System.out.println("Element główny: " + rootName);
NodeList bookNodeList = root.getElementsByTagName("book");
int n = bookNodeList.getLength();
System.out.println("Liczba książek: " + n);
NodeList bookNodeList = root.getElementsByTagName("book");
int n = bookNodeList.getLength();
for(int i=0; i<n; i++) {
Node bookNode = bookNodeList.item(i);
NodeList childNodes = bookNode.getChildNodes();
for(int j=0; j<childNodes.getLength(); j++) {
Node node = childNodes.item(j);
if(node.getNodeType() == Node.ELEMENT_NODE &&
node.getNodeName().equals("title")) {
String title = node.getTextContent();
System.out.println(title);
}
}
}

JAXB – Java Architecture for XML Binding
 Mapowanie klas na reprezentację XML
 Specyfikacja mapowania za pomocą adnotacji
 Możliwość automatycznego generowania klas i adnotacji
na podstawie XML Schema
@XmlType(name = "book")
public class Book {
private
private
private
private
private
private
private
String id;
String title;
String author;
String isbn;
Integer year;
String publisher;
Integer pages;
@XmlAttribute
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
<?xml version="1.0" ?>
<books>
<book id="a001">
<title>Java i XML</tytul>
<author>B. McLaughlin</author>
<publisher>Helion</publisher>
<year>2007</year>
<pages>440</pages>
</book>
</books>
@XmlType(name = "book")
public class Book {
private
private
private
private
private
private
private
String id;
String title;
List<String> authors;
String isbn;
Integer year;
String publisher;
Integer pages;
@XmlElementWrapper(name = "authors")
@XmlElement(name = "author")
public List<String> getAuthors() {
return authors;
}
<?xml version="1.0" ?>
<books>
<book id="a001">
<title>Java i XML</tytul>
<authors>
<author>B. McLaughlin</author>
<author>J. Edelson</author>
</authors>
<publisher>Helion</publisher>
<year>2007</year>
<pages>440</pages>
</book>
</books>
<?xml version="1.0" ?>
<books>
@XmlRootElement(name = "books")
public class BookList {
<book id="a001">
...
</book>
private List<Book> bookList =
new ArrayList<Book>();
@XmlElement(name = "book")
public List<Book> getBookList() {
return bookList;
}
<book id="xb07">
...
</book>
</books>
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
}
JAXBContext context = JAXBContext.newInstance(BookList.class);
Unmarshaller um = context.createUnmarshaller();
FileReader fr = new FileReader("books.xml");
BookList bl = (BookList) um.unmarshal(fr);
fr.close();
for(Book b : bl.getBookList())
System.out.println(b.getId() + " " + b.getTitle());


XML Path Language
Adresowanie części dokumentu XML

Przykłady ścieżek
 Element:
 Atrybut:
/books/book/title
/books/book/@id

/books/book/title

/books/book/@id

/books/book[@id="172"]

//person

//person [ profile/age<25 and
profile/gender='female' ] / name

Funkcje operujące na liczbach:
 fn:abs(...)
 fn:round(...), fn:floor(...), fn:ceiling(...)
 fn:avg(…), fn:min(…), fn:max(…)

Operacje na łańcuchach tekstowych:
 fn:concat(string1, string2)
 fn:substring(string, start, length)
 fn:string-length(...)
 fn:lower-case(...), fn:upper-case(...)
 fn:contains(string1, string2), fn:starts-with(string1, string2)

//book[ starts-with(title, "Java") ]

//book[ contains(title, "Java") ]/title

//book[ count(//author)>1 ]/title

//book[ string-length(title)>100 ]/title
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse("test100k.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
String name =
xpath.evaluate("//person[@id='person1']/name", doc);
String card =
xpath.evaluate("//person[name='Nagasaki']/creditcard", doc);
String expr1 =
"//person[profile/age<25 and profile/gender='female']/name";
NodeList nodes = (NodeList) xpath.evaluate(expr1, doc,
XPathConstants.NODESET);
for(int i=0; i<nodes.getLength(); i++) {
Node n = nodes.item(i);
System.out.println(n.getTextContent());
}
String expr2 =
"//person[profile/age<25 and profile/gender='female']";
NodeList nodes2 = (NodeList) xpath.evaluate(expr2, doc,
XPathConstants.NODESET);
for(int i=0; i<nodes2.getLength(); i++) {
Node n = nodes2.item(i);
String name = xpath.evaluate("name", n);
String age = xpath.evaluate("profile/age", n);
String email = xpath.evaluate("emailaddress", n);
System.out.println(name + ", " + age + ", " + email);
}
Transformacje XSLT

XSL Transformations
 Język przekształceń dokumentów XML
 Tłumaczenie dokumentu XML z
jednego formatu na inny

Arkusz XSLT
 „Przepis” na transformację
 Zbudowany z reguł
 Wykorzystanie XPath
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<books>
<xsl:apply-templates select="//ksiazka[(marka='1' or marka='2') and typ='1' and status='1']" />
</books>
</xsl:template>
<xsl:template match="//ksiazka">
<book id="{@ident}">
<title>
<xsl:value-of select="tytul[@language='polski']" />
</title>
<author>
<xsl:value-of select="autor" />
</author>
<isbn>
<xsl:value-of select="isbn" />
</isbn>
<publisher>
<xsl:choose>
<xsl:when test="marka=1">Helion</xsl:when>
<xsl:when test="marka=2">Onepress</xsl:when>
</xsl:choose>
</publisher>
<year>
<xsl:value-of select="substring(datawydania, 1, 4)" />
</year>
<pages>
<xsl:value-of select="liczbastron" />
</pages>
</book>
</xsl:template>
</xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0„
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<books>
<xsl:apply-templates select="//ksiazka[(marka='1' or
marka='2') and typ='1' and status='1']" />
</books>
</xsl:template>
<xsl:template match="//ksiazka">
...
</xsl:template>
</xsl:stylesheet>
<xsl:template match="//ksiazka">
<book id="{@ident}">
<title>
<xsl:value-of select="tytul[@language='polski']" />
</title>
<author>
<xsl:value-of select="autor" />
</author>
...
<publisher>
<xsl:choose>
<xsl:when test="marka=1">Helion</xsl:when>
<xsl:when test="marka=2">Onepress</xsl:when>
</xsl:choose>
</publisher>
<year>
<xsl:value-of select="substring(datawydania, 1, 4)" />
</year>
...
</book>
</xsl:template>