Академический Документы
Профессиональный Документы
Культура Документы
An Introduction to XML and Web Technologies 3 An Introduction to XML and Web Technologies 4
1
JDOM Classes and Interfaces A Simple Example
An Introduction to XML and Web Technologies 5 An Introduction to XML and Web Technologies 6
An Introduction to XML and Web Technologies 7 An Introduction to XML and Web Technologies 8
2
A Final Example (2/3) A Final Example (3/3)
An Introduction to XML and Web Technologies 9 An Introduction to XML and Web Technologies 10
An Introduction to XML and Web Technologies 11 An Introduction to XML and Web Technologies 12
3
Validation (XML Schema) XPath Evaluation
public class ValidateXMLSchema {
public static void main(String[] args) { void doubleSugar(Document d) throws JDOMException {
try { XPath p = XPath.newInstance("//rcp:ingredient[@name='sugar']");
SAXBuilder b = new SAXBuilder(); p.addNamespace("rcp","http://www.brics.dk/ixwt/recipes");
b.setValidation(true); java.util.Iterator i = p.selectNodes(d).iterator();
b.setProperty( while (i.hasNext()) {
"http://java.sun.com/xml/jaxp/properties/schemaLanguage", Element e = (Element)i.next();
"http://www.w3.org/2001/XMLSchema"); double amount = e.getAttribute("amount").getDoubleValue();
String msg = "No errors!"; e.setAttribute("amount",new Double(2*amount).toString());
try { }
Document d = b.build(new File(args[0])); }
} catch (JDOMParseException e ) {
msg = e.getMessage();
}
System.out.println(msg);
} catch (Exception e) { e.printStackTrace(); }
}
}
An Introduction to XML and Web Technologies 13 An Introduction to XML and Web Technologies 14
4
Business Card Editor Class Representation
class Card {
public String name,title,email,phone,logo;
An Introduction to XML and Web Technologies 17 An Introduction to XML and Web Technologies 18
Vector doc2vector(Document d) {
Vector v = new Vector(); Document vector2doc() {
Iterator i = d.getRootElement().getChildren().iterator(); Element cardlist = new Element("cardlist");
while (i.hasNext()) { for (int i=0; i<cardvector.size(); i++) {
Element e = (Element)i.next(); Card c = (Card)cardvector.elementAt(i);
String phone = e.getChildText("phone",b);
if (c!=null) {
if (phone==null) phone="";
Element card = new Element("card",b);
Element logo = e.getChild("logo",b);
String uri; Element name = new Element("name",b);
if (logo==null) uri=""; name.addContent(c.name); card.addContent(name);
else uri=logo.getAttributeValue("uri"); Element title = new Element("title",b);
Card c = new Card(e.getChildText("name",b), title.addContent(c.title); card.addContent(title);
e.getChildText("title",b), Element email = new Element("email",b);
e.getChildText("email",b),
email.addContent(c.email); card.addContent(email);
phone, uri);
v.add(c);
}
return v;
}
An Introduction to XML and Web Technologies 19 An Introduction to XML and Web Technologies 20
5
From Classes to JDOM (2/2) A Little Bit of Code
An Introduction to XML and Web Technologies 21 An Introduction to XML and Web Technologies 22
An Introduction to XML and Web Technologies 23 An Introduction to XML and Web Technologies 24
6
Binding Compilers The JAXB Framework
An Introduction to XML and Web Technologies 25 An Introduction to XML and Web Technologies 26
An Introduction to XML and Web Technologies 27 An Introduction to XML and Web Technologies 28
7
Business Card Schema (3/3) The org.businesscard Package
An Introduction to XML and Web Technologies 29 An Introduction to XML and Web Technologies 30
An Introduction to XML and Web Technologies 31 An Introduction to XML and Web Technologies 32
8
The Main Application Streaming XML
An Introduction to XML and Web Technologies 33 An Introduction to XML and Web Technologies 34
View the XML document as a stream of events: public class Trace extends DefaultHandler {
• the document starts int indent = 0;
9
Tracing All Events (2/4) Tracing All Events (3/4)
An Introduction to XML and Web Technologies 37 An Introduction to XML and Web Technologies 38
An Introduction to XML and Web Technologies 39 An Introduction to XML and Web Technologies 40
10
A Simple Streaming Example (1/2) A Simple Streaming Example (2/2)
public class Height extends DefaultHandler { public static void main(String[] args) {
int h = -1; try {
int max = 0; Height handler = new Height();
XMLReader reader = XMLReaderFactory.createXMLReader();
public void startElement(String uri, String localName, reader.setContentHandler(handler);
String qName, Attributes atts) { reader.parse(args[0]);
h++; if (h > max) max = h; System.out.println(handler.max);
} } catch (Exception e) { e.printStackTrace(); }
}
public void endElement(String uri, String localName, }
String qName) {
h--;
}
An Introduction to XML and Web Technologies 43 An Introduction to XML and Web Technologies 44
11
SAX May Emulate JDOM (2/2) Using Contextual Information
12
Contextual Information in SAX (3/3) SAX Filters
public void endElement(String uri, String localName,
String qName) {
if (uri.equals("http://www.w3.org/1999/xhtml")) A SAX application may be turned into a filter
if (localName.equals("form"))
formheight--;
Filters may be composed (as with pipes)
} A filter is an event handler that may pass events
public static void main(String[] args) { along in the chain
try {
CheckForms handler = new CheckForms();
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader.parse(args[0]);
} catch (Exception e) { e.printStackTrace(); }
}
}
An Introduction to XML and Web Technologies 49 An Introduction to XML and Web Technologies 50
An Introduction to XML and Web Technologies 51 An Introduction to XML and Web Technologies 52
13
A SAX Filter Example (3/4) A SAX Filter Example (4/4)
An Introduction to XML and Web Technologies 53 An Introduction to XML and Web Technologies 54
• the programmer has the initiative public static void main (String args[])
throws XmlPullParserException, IOException {
• the parser must react to requests XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
int formheight = 0;
HashSet formnames = new HashSet();
An Introduction to XML and Web Technologies 55 An Introduction to XML and Web Technologies 56
14
Contextual Information in XMLPull (2/3) Contextual Information in XMLPull (3/3)
xpp.setInput(new FileReader(args[0])); else if (eventType==XmlPullParser.END_TAG) {
int eventType = xpp.getEventType(); if (xpp.getNamespace().equals("http://www.w3.org/1999/xhtml")
while (eventType!=XmlPullParser.END_DOCUMENT) { && xpp.getName().equals("form"))
if (eventType==XmlPullParser.START_TAG) { formheight--;
if (xpp.getNamespace().equals("http://www.w3.org/1999/xhtml") }
&& xpp.getName().equals("form")) { eventType = xpp.next();
if (formheight>0) }
report(xpp,"nested forms"); }
String name = xpp.getAttributeValue("","name"); }
if (formnames.contains(name))
report(xpp,"duplicate form name");
else
formnames.add(name);
formheight++;
} else if (xpp.getName().equals("input") ||
xpp.getName().equals("select") ||
xpp.getName().equals("textarea"))
if (formheight==0)
report(xpp,"form field outside form");
} }
An Introduction to XML and Web Technologies 57 An Introduction to XML and Web Technologies 58
Not that different from the push version SAX allows the programming of streaming
More direct programming style applications "by hand"
Smaller memory footprint XSLT allows high-level programming of
Pipelining with filter chains is not available applications
(but may be simulated in languages with higher- A broad spectrum of these could be streamed
order functions) But XSLT does not allow streaming...
An Introduction to XML and Web Technologies 59 An Introduction to XML and Web Technologies 60
15
STX Similarities with XSLT
An Introduction to XML and Web Technologies 61 An Introduction to XML and Web Technologies 62
An Introduction to XML and Web Technologies 63 An Introduction to XML and Web Technologies 64
16
STXPath Syntax STXPath Semantics
Must use abbreviated XPath 2.0 syntax Evaluate the corresponding XPath 2.0 expression
The axes following and preceding are not Restrict the result to those nodes that are on the
available ancestor axis
Extra node tests: cdata() and doctype() <A>
<B/>
<C><D/></C>
</A>
Evaluate count(//B) with D as the context node
With XPath the result is 1
With STXPath the result is 0
An Introduction to XML and Web Technologies 65 An Introduction to XML and Web Technologies 66
An Introduction to XML and Web Technologies 67 An Introduction to XML and Web Technologies 68
17
SAX Version (1/2) SAX Version (2/2)
An Introduction to XML and Web Technologies 71 An Introduction to XML and Web Technologies 72
18
Mutable Variables STX Version of CheckForms (1/2)
<person>
<person> <emails>
<email/><email/><email/> <email/><email/><email/>
<phone/><phone/> </emails>
</person> <phone/><phone/>
</person>
An Introduction to XML and Web Technologies 75 An Introduction to XML and Web Technologies 76
19
Groups (2/2) Limitations of Streaming
<stx:template match="phone">
<phone/> <xsl:template name="mirror" match="/|@*|node()">
</stx:template> <xsl:copy>
</stx:transform> <xsl:apply-templates select="@*"/>
<xsl:apply-templates select="reverse(node())"/>
<person> </xsl:copy>
<person> <emails>
<email/><email/><email/>
</xsl:template>
<email/><email/><email/>
<phone/><phone/> </emails> </xsl:stylesheet>
</person> <phone/><phone/>
</person>
An Introduction to XML and Web Technologies 77 An Introduction to XML and Web Technologies 78
An Introduction to XML and Web Technologies 79 An Introduction to XML and Web Technologies 80
20
STX for Recipes (3/7) STX for Recipes (4/7)
<stx:template match="rcp:recipe"> <stx:template match="rcp:ingredient" >
<tr> <ul><stx:process-self group="inner"/></ul>
<td> </stx:template>
<stx:process-children/>
</td> <stx:template match="rcp:preparation">
</tr> <ol><stx:process-children/></ol>
</stx:template> </stx:template>
An Introduction to XML and Web Technologies 81 An Introduction to XML and Web Technologies 82
21
STX for Recipes (7/7) XML in Programming Languages
An Introduction to XML and Web Technologies 85 An Introduction to XML and Web Technologies 86
Type-
Type-Safe XML Programming Languages XDuce
An Introduction to XML and Web Technologies 87 An Introduction to XML and Web Technologies 88
22
XDuce Types for Recipes (1/2) XDuce Types for Recipes (2/2)
namespace rcp = "http://www.brics.dk/ixwt/recipes" type Ingredient = rcp:ingredient[@name[String],
@amount[String]?,
type Collection = rcp:collection[Description,Recipe*] @unit[String]?,
type Description = rcp:description[String] (Ingredient*,Preparation)?]
type Recipe = rcp:recipe[@id[String]?, type Preparation = rcp:preparation[Step*]
Title, type Step = rcp:step[String]
Date, type Comment = rcp:comment[String]
Ingredient*, type Nutrition = rcp:nutrition[@calories[String],
Preparation, @carbohydrates[String],
Comment?, @fat[String],
Nutrition, @protein[String],
Related*] @alcohol[String]?]
type Title = rcp:title[String] type Related = rcp:related[@ref[String],String]
type Date = rcp:date[String]
An Introduction to XML and Web Technologies 89 An Introduction to XML and Web Technologies 90
An Introduction to XML and Web Technologies 91 An Introduction to XML and Web Technologies 92
23
From Recipes to Tables (2/3) From Recipes to Tables (3/3)
fun extractNutrition(val t as String, val n as Nutrition) : Dish = | rcp:nutrition[@calories[val calories],
match n with @carbohydrates[val carbohydrates],
rcp:nutrition[@calories[val calories], @fat[val fat],
@carbohydrates[val carbohydrates], @protein[val protein]]
@fat[val fat], -> dish[@name[t],
@protein[val protein], @calories[calories],
@alcohol[val alcohol]] @carbohydrates[carbohydrates],
-> dish[@name[t], @fat[fat],
@calories[calories], @protein[protein],
@carbohydrates[carbohydrates], @alcohol["0%"]]
@fat[fat],
@protein[protein],
@alcohol[alcohol]] let val collection = validate load_xml("recipes.xml") with Collection
let val _ = print(extractCollection(collection))
An Introduction to XML and Web Technologies 93 An Introduction to XML and Web Technologies 94
The XDuce type checker determines that: A Java framework (like JDOM) but:
• every function returns a valid value • it is based on immutable templates, which are
• every function argument is a valid value sequences of XML trees containing named gaps
• every match has an exhaustive collection of patterns • XML trees are constructed by plugging gaps
• every pattern matches some value • it has syntactic sugar for template constants
Clearly, this will eliminate many potential errors • XML is navigated using XPath
• an analyzer can a compile-time guarantee that an XML
expression is valid according to a given DTD
An Introduction to XML and Web Technologies 95 An Introduction to XML and Web Technologies 96
24
Business Cards to Phone Lists (1/2) Business Cards to Phone Lists (2/2)
import dk.brics.xact.*; XML cardlist = XML.get("file:cards.xml",
import java.io.*; "file:businesscards.dtd",
"http://businesscard.org");
public class PhoneList { XML x = wrapper.plug("TITLE", "My Phone List")
public static void main(String[] args) throws XactException { .plug("MAIN", [[<h:ul><[CARDS]></h:ul>]]);
String[] map = {"c", "http://businesscard.org",
"h", "http://www.w3.org/1999/xhtml"};
XML.setNamespaceMap(map); XMLIterator i = cardlist.select("//c:card[c:phone]").iterator();
while (i.hasNext()) {
XML wrapper = [[<h:html> XML card = i.next();
<h:head> x = x.plug("CARDS",
<h:title><[TITLE]></h:title> [[<h:li>
</h:head> <h:b><{card.select("c:name/text()")}></h:b>,
<h:body> phone: <{card.select("c:phone/text()")}>
<h:h1><[TITLE]></h:h1> </h:li>
<[MAIN]> <[CARDS]>]]);
</h:body> }
</h:html>]]; System.out.println(x);
}
}
An Introduction to XML and Web Technologies 97 An Introduction to XML and Web Technologies 98
An Introduction to XML and Web Technologies 99 An Introduction to XML and Web Technologies 100
25
A Flattened Recipe A Recipe Flattener in XACT (1/2)
<rcp:recipe id="117"> public class Flatten {
<rcp:title>Fried Eggs with Bacon</rcp:title> static final String rcp = "http://www.brics.dk/ixwt/recipes";
<rcp:date>Fri, 10 Nov 2004</rcp:date> static final String[] map = { "rcp", rcp };
<rcp:ingredient name="egg" amount="2"/>
<rcp:ingredient name="bacon" amount="3" unit="strip"/> static { XML.setNamespaceMap(map); }
<rcp:preparation>
<rcp:step>Break the eggs into a bowl.</rcp:step> public static void main(String[] args) throws XactException {
<rcp:step>Fry until ready.</rcp:step> XML collection = XML.get("file:recipes.xml",
<rcp:step>Fry the bacon until crispy.</rcp:step> "file:recipes.dtd", rcp);
<rcp:step>Serve with the eggs.</rcp:step> XML recipes = collection.select("//rcp:recipe");
</rcp:preparation> XML result = [[<rcp:collection>
<rcp:nutrition calories="517" <{collection.select("rcp:description")}>
fat="64%" carbohydrates="0%" protein="36%"/> <[MORE]>
</rcp:recipe> </rcp:collection>]];
An Introduction to XML and Web Technologies 101 An Introduction to XML and Web Technologies 102
An Introduction to XML and Web Technologies 103 An Introduction to XML and Web Technologies 104
26
Caught at Compile-
Compile-Time Essential Online Resources
*** Invalid XML at line 31
sub-element 'rcp:ingredient' of element 'rcp:collection' not declared
required attribute 'name' missing in element 'rcp:ingredient'
http://www.jdom.org/
sub-element 'rcp:title' of element 'rcp:ingredient' not declared
sub-element 'rcp:related' of element 'rcp:ingredient' not declared
http://java.sun.com/xml/jaxp/
sub-element 'rcp:nutrition' of element 'rcp:ingredient' not declared
sub-element 'rcp:date' of element 'rcp:ingredient' not declared
http://java.sun.com/xml/jaxb/
http://www.saxproject.org/
An Introduction to XML and Web Technologies 105 An Introduction to XML and Web Technologies 106
27