abgeleitet von SGML, siehe xmlTutor , IBM-Tutorial
Eine deutschsprachige Einführung findet man beim XmlguruEin XML-Dokument ist eine Asci-Textdatei. Es kann als Textdatei mit einem beliebigen Editor editiert werden und zur Kontrolle von einem Browser angezeigt werden. Der Browser zeigt die hierarchische Struktur des XML-Dokuments, rote Minuszeichen bei übergeordneten Elementen.
Ein XML-Dokument besteht aus Elementen, das sind mit Namen versehene Container für Inhalte. Ein Element besteht aus Tag am Anfang, Inhalt und Tag am Schluss.
XML ist eine Auszeichnungssprache mit inhaltlich orientierten Tags: Tags beschreiben den Inhalt der Daten in einem XML-Dokument. Jeder Tag muss Anfang und Ende haben:
<ein_Tag> ein Inhalt </ein_Tag>
Tags können ineinander geschachtelt werden
Beispiel Sonett 130Es besteht eine absolute Trennung von Inhalt und Formatierung. Die Tags beschreiben den Inhalt, so dass geeignete Programme den Inhalt entsprechend den Vorschriften verarbeiten können, die dem Tag irgendwie zugeordnet werden. XML-Dokumente sind nicht dazu bestimmt, direkt ausgegeben zu werden, sondern werden mit geeigneten Programmen weiterverarbeitet.
Da die XML-Tags inhaltlich definiert sind, können diese Programme zur Weiterverarbeitung ganz unterschiedliche Themen betreffen:
XML-Dokumente erfüllen verschiedene Grade von
Korrektheit: XML-Dokumente sind entweder wellformed (wohlgeformt)
oder valid (gültig).
Jedes XML-Dokument beginnt mit einer XML-Deklarationen, z.B.:
<?xml version="1.0"?>Jedes XML-Dokument hat 1 Root-Element, ein minimales Dokument könnte folgendermassen aussehen:
<?xml version="1.0"?> <buchliste> </buchliste>
<Buch Empfehlung="1"> <Autor>Tor Heiertal</Autor> </Buch> <Buch Empfehlung="6"> <Autor>Marlene Dietrich</Autor> </Buch>
XML-Dokumente müssen erst mal 1 Kriterium genügen: wellformed ist ein Dokument dann, wenn jeder Tag einen Abschluss hat und wenn hierarchisch ineinander verschachtelte Tags sich nicht überlappen: ein Tag, der innerhalb eines anderen geöffnet wird, muss auch innerhalb wieder geschlossen werden.
Eine minimale DTD für ein Dokument sieht so aus:
<!DOCTYPE Dokument []>
wobei in den eckigen Klammern die Deklarationen stehen.
Document Type Desription legt fest, welche Elemente
Bestandteile eines XML-Dokuments sind.
Die DTD bestimmt also, welche Tags in einem Dokument
vorkommen (können/müssen) und welche Tags
in andere Tags verschachtelt werden können.
Form der Definition ist <!ELEMENT Name Wert>
Elemente kommen optional oder obligatorisch, einmal oder mehrmals vor:
| A? | das Element A kommt optional vor |
| A+ | das Element A kommt 1 oder mehrmals vor |
| A* | das Element A kommt 0 oder mehrmals vor |
| A|B | das Element A oder das Element B |
| A,B | das Element A gefolgt von Element B |
| (A,B)? | ebenso optional |
| #PCDATA? | eine beliebige Zeichenkette im btr. character-encoding |
Die DTD kann im XML-Dokument selbst oder in einer separaten Datei stehen.
Attribute zu Element hinzufügen in der Form:
<!ATTLIST zuElement AttributName AttributDefinition>
Es gibt verschiedene Arten von Attributen:
Ein XML-Dokument mit seinen Tags ist als eine Baumstruktur
aufzufassen. Als Wurzel fungiert immer ein Tag namens "/", darunter kommt
das oberste/äusserste Tag, dann die darin verschachtelten Tags.
Die anderen, unter der Wurzel neben- und ineinander
geschachtelten Tags sind die Zweige oder Knoten (nodes) der Baumstruktur.
Jeder Zweig endet mit mit einem terminalen Knoten, dort ist meistens Inhalt.
Manche Programme, die XML-Dokumente verarbeiten, sind in der Lage Baumstrukturen rekursiv zu verarbeiten, andere verarbeiten das Dokument sequentiell.
Ein XML-Parser ist ein Programm, das ein XML-Dokument liest und dessen
Struktur anderen Programmen zur weiteren Verarbeitung zur Verfügung stellt.
Beim Lesen der XML-Datei überprüft der Parser die Datei auf die
Eigenschaft wellformed und/oder valid
der Inhalt eines XML-Dokuments ist immer ASCI-Text in einer bestimmten character-encoding.
Ein XT ( XML-Transformationsprogramm ) ist ein Programm, das ein
XML-Dokument in ein anderes XML-Dokument umformt. Ein source-tree
wird in einen result-tree umgewandelt. Die Form der
Umwandlung wird dabei von einer XSL-Datei bestimmt.
Die XSL (Extended Style Language) bestimmt die Umwandlungen
mit verschiedenen Sorten von Regeln :
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/TR/xhtml1/strict"> <--Template-Rules --> </xsl:stylesheet>
<xsl:template match="Name des btr. Tags">
<--Instructions -->
<xsl:template>
Template-Rules regeln die Verarbeitung eines XML-Tags. Der btr.
Tag wird mit match="Tag" angesprochen. In den
Instructions wird angegeben, was mit den Elementen innerhalb des Tags zu
geschehen hat.
C:>xt shakespeare.xml shakespeare.xsl Shakespeare.htmlund erzeugt, falls keine Fehlermeldungen kommen, eine HTML-Datei.
Die Anwendung von XSL ist dokumentiert in einem
w3c-Dokument.
Gewisse Browser wie der IE5.0 können XML-Dokumente mittels
eines geeigneten XSL-Stylesheetdokuments auch direkt in ein HTML-
Dokument umwandeln.
Der Anfang des Sonetts 130 als XML-Dokument sieht dann so aus:
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="shakespeare1.xsl"?> <sonnet type="Shakespearean">Das XSL-Stylesheet muss einen anderen Namespace ( http://www.w3.org/TR/WD-xsl ) benutzen und es muss detailliert alle Tags etc benennen, weil hier keinerlei Standardeinstellungen etc. angewendet werden. Beispiel XML-Datei. XSL-Datei.
XML-verarbeitende Programme in Java zu schreiben ist naheliegend, da Java-Servlets auf dem Server laufen; XML plus Java bietet sich also an, um Server-Output bei Anfrage des Client zu erzeugen. Es ist aber auch möglich, XML mit einfachen Java- Applications zu verarbeiten.
Solche Programme müssen
Es haben sich verschiedene Standards zur Bearbeitung von XML
in Java-Programmen herausgebildet.
Das Document Object Model
(DOM) stellt Klassen, Schnittstellen und Methoden zur
Verfügung, die eine hierarchische interne Darstellung eines
XML-Dokuments erlauben.
Die Simple API for XML (SAX) bearbeitet das XML-Dokument
sequenziell von oben nach unten.
Diese API inkl. DOM und SAX gibt es bei SUN zum Herunterladen unter dem Namen Java API for XML Parsing. Es existieren aber auch viele andere Implementationen: Dieses Gebiet ist noch im Fluss.
DOM-API gibt dem Programmierer aus Java heraus Zugriff
auf XML.
DOM stellt das komplette XML-Dokument als Baumstruktur
im Arbeitspeicher zur Verarbeitung bereit, daher hoher
Speicherbedarf.
DOM kann vorhandenes XML-Dokument verarbeiten oder
neues XML-Dokument erzeugen.
Beispiel Parser1.java
stellt ein XML-Dokument mittels System.out.println() dar.
Beispiel XmlDoc.java
geht umgekehrt vor und erzeugt ein XML-Dokument.
Die Verarbeitung eines XML-Dokuments:
SAX geht sequentiell durch das XML-Dokument und reagiert auf dessen Elemente wenn es sie antrifft: Der Parser führt einen Handler mit, der XML-Elemente wie z.B. den Beginn eines Tags erkennt und irgendwie reagiert. SAX kann keine Dokumente erzeugen.
In der Praxis sollte ein solche Servlet im Rahmen einer Servlet-Chain arbeitsteilig auf dem Server arbeiten:
<!ELEMENT sonett (author,title,lines)> <!ATTLIST sonett type CDATA > <!ELEMENT author (last-name, first-name,nationality, year-of-birth)> <!ELEMENT last-name (#PCDATA)> <!ELEMENT first-name (#PCDATA)> <!ELEMENT first-name (#PCDATA)> <!ELEMENT nationality (#PCDATA)> <!ELEMENT yeart-of-birth (#PCDATA)> <!ELEMENT title (#PCDATA)> <!ELEMENT lines line+ > <!ELEMENT line (#PCDATA)>
// einfacher DOM-Parser
// zum Parsen und Anzeigen von Dokumenten
// .xml
// .html
// 8.7.00 AG
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class Parser1
{
public static void main( String [] arg )
{
if( arg.length != 1 )
{
System.out.println( "\nDateiname der XML?");
System.exit(0);
}
String DateiName = arg[0];
try
{
Document D = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new File( DateiName ));
dokumentAnzeigen( D );
}
catch( Exception e )
{
System.out.println( "XML-Datei nicht gef. od. sonst. Fehler");
System.exit(0);
}
}
static void dokumentAnzeigen( Document docu )
{
Element E = docu.getDocumentElement();
System.out.print( E );
}
}
// einfacher validierender DOM-Parser
// zum Parsen und Anzeigen von Dokumenten .xml
// falls sie ein DTD vorzuweisen haben
// und dieses korrekt umgesetzt wird
// benutzt ParserValError.class
// 18.7.00 AG
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class ParserVal
{
public static void main( String [] arg )
{
if( arg.length != 1 )
{
System.out.println( "\nDateiname der XML?");
System.exit(0);
}
String DateiName = arg[0];
ParserValError PVE = new ParserValError();
try
{
DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance();
DBF.setValidating(true);
DocumentBuilder DB =DBF.newDocumentBuilder();
DB.setErrorHandler( PVE );
Document D = DB.parse(new File( DateiName ));
dokumentAnzeigen( D );
}
catch( org.xml.sax.SAXParseException spe )
{
System.out.println( "\n\n"+spe.toString());
}
catch( Exception e )
{
System.out.println( e.toString());
System.out.println( "XML-Datei nicht gef. od. sonst. Fehler");
System.exit(0);
}
}
static void dokumentAnzeigen( Document docu )
{
Element E = docu.getDocumentElement();
System.out.print( E );
}
}
// ErrorHAndler fuer den einfachen validierenden DOM-Parser
// beendet den Parser wenn DTD falsch oder fehlend
// mit einer Fehlermeldung von SAXParseException
//
// 19.7.00 AG
import org.xml.sax.*;
public class ParserValError extends Throwable
implements org.xml.sax.ErrorHandler
{
public void fatalError(SAXParseException sx)
{
}
public void error(SAXParseException e) throws SAXParseException
{
throw e;
}
public void warning(SAXParseException err)
{
}
}
//---------------------------------------------------------------------------||
// XmlDoc.java ||
// ||
// This code generates an XML document from a portion of a DOM tree. ||
//---------------------------------------------------------------------------||
// Written 17 February 2000 by Doug Tidwell. ||
//---------------------------------------------------------------------------||
// siehe: http://www.ibm.com/software/developer/library/servlets-and-xml/ ||
//-----umgebaut 7.7.00 AG----------------------------------------------------||
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class XmlDoc
{
Document doc = null;
Element author = null;
Element lines = null;
Element title = null;
static public void main(String [] args )
{
XmlDoc XD = new XmlDoc();
XD.doc = XD.neuesDoc();
XD.printDOMTree(XD.doc);
}
public Document neuesDoc()
{
DocumentBuilderFactory docBFac;
DocumentBuilder docBuild;
try
{
docBFac = DocumentBuilderFactory.newInstance();
docBuild = docBFac.newDocumentBuilder();
doc = docBuild.newDocument();
}
catch( Exception e )
{
System.out.println("Dokument konnte nicht erzeugt werden");
}
if (doc != null)
{
Element root = doc.createElement("sonnet");
root.setAttribute("type", "Shakespearean");
author = doc.createElement("author");
Element lastName = doc.createElement("last-name");
lastName.appendChild(doc.createTextNode("Shakespeare"));
author.appendChild(lastName);
Element firstName = doc.createElement("first-name");
firstName.appendChild(doc.createTextNode("William"));
author.appendChild(firstName);
Element nationality = doc.createElement("nationality");
nationality.appendChild(doc.createTextNode("British"));
author.appendChild(nationality);
Element yearOfBirth = doc.createElement("year-of-birth");
yearOfBirth.appendChild(doc.createTextNode("1564"));
author.appendChild(yearOfBirth);
Element yearOfDeath = doc.createElement("year-of-death");
yearOfDeath.appendChild(doc.createTextNode("1616"));
author.appendChild(yearOfDeath);
root.appendChild(author);
title = doc.createElement("title");
title.appendChild(doc.createTextNode("Sonnet 130"));
root.appendChild(title);
lines = doc.createElement("lines");
Element line01 = doc.createElement("line");
line01.appendChild(doc.createTextNode("My mistress' eyes are nothing like the sun,"));
lines.appendChild(line01);
Element line02 = doc.createElement("line");
line02.appendChild(doc.createTextNode("Coral is far more red than her lips red."));
lines.appendChild(line02);
Element line03 = doc.createElement("line");
line03.appendChild(doc.createTextNode("If snow be white, why then her breasts are dun,"));
lines.appendChild(line03);
Element line04 = doc.createElement("line");
line04.appendChild(doc.createTextNode("If hairs be wires, black wires grow on her head."));
lines.appendChild(line04);
Element line05 = doc.createElement("line");
line05.appendChild(doc.createTextNode("I have seen roses damasked, red and white,"));
lines.appendChild(line05);
Element line06 = doc.createElement("line");
line06.appendChild(doc.createTextNode("But no such roses see I in her cheeks."));
lines.appendChild(line06);
Element line07 = doc.createElement("line");
line07.appendChild(doc.createTextNode("And in some perfumes is there more delight"));
lines.appendChild(line07);
Element line08 = doc.createElement("line");
line08.appendChild(doc.createTextNode("Than in the breath that from my mistress reeks."));
lines.appendChild(line08);
Element line09 = doc.createElement("line");
line09.appendChild(doc.createTextNode("I love to hear her speak, yet well I know"));
lines.appendChild(line09);
Element line10 = doc.createElement("line");
line10.appendChild(doc.createTextNode("That music hath a far more pleasing sound."));
lines.appendChild(line10);
Element line11 = doc.createElement("line");
line11.appendChild(doc.createTextNode("I grant I never saw a goddess go,"));
lines.appendChild(line11);
Element line12 = doc.createElement("line");
line12.appendChild(doc.createTextNode("My mistress when she walks, treads on the ground."));
lines.appendChild(line12);
Element line13 = doc.createElement("line");
line13.appendChild(doc.createTextNode("And yet, by Heaven, I think my love as rare"));
lines.appendChild(line13);
Element line14 = doc.createElement("line");
line14.appendChild(doc.createTextNode("As any she belied with false compare."));
lines.appendChild(line14);
root.appendChild(lines);
doc.appendChild(root);
}
return doc;
}
/** Prints the specified node, recursively. */
public void printDOMTree(Node node )
{
int type = node.getNodeType();
switch (type)
{
// print the document element
case Node.DOCUMENT_NODE:
{
printDOMTree(((Document)node).getDocumentElement() );
break;
}
// print element with attributes
case Node.ELEMENT_NODE:
{
System.out.print("<");
System.out.print(node.getNodeName());
NamedNodeMap attrs = node.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node attr = attrs.item(i);
System.out.print(" " + attr.getNodeName() +
"=\"" + attr.getNodeValue() +
"\"");
}
System.out.print(">");
NodeList children = node.getChildNodes();
if (children != null)
{
int len = children.getLength();
for (int i = 0; i < len; i++)
printDOMTree(children.item(i));
}
break;
}
// handle entity reference nodes
case Node.ENTITY_REFERENCE_NODE:
{
System.out.print("&");
System.out.print(node.getNodeName());
System.out.println(";");
break;
}
// print cdata sections
case Node.CDATA_SECTION_NODE:
{
System.out.print("<![CDATA[");
System.out.print(node.getNodeValue());
System.out.println("]]>");
break;
}
// print text
case Node.TEXT_NODE:
{
System.out.print(node.getNodeValue());
break;
}
// print processing instruction
case Node.PROCESSING_INSTRUCTION_NODE:
{
System.out.println("<?");
System.out.print(node.getNodeName());
String data = node.getNodeValue();
{
System.out.print(" ");
System.out.print(data);
}
System.out.println("?>");
break;
}
}
if (type == Node.ELEMENT_NODE)
{
System.out.print("</");
System.out.print(node.getNodeName());
System.out.println('>');
}
} // DOMTree(Node, PrintWriter)
}
// aus dem SUN-Tutorial
//http://java.sun.com/xml/docs/tutorial/sax/2a_echo.html
//
//liest XML oder HTML und stellt die Struktur dar
import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
public class Echo extends HandlerBase
{
static private Writer out;
private String indentString = " ";
private int indentLevel = 0;
public static void main (String argv[])
{
if (argv.length != 1)
{
System.err.println ("Usage: cmd filename");
System.exit (1);
}
try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
out = new OutputStreamWriter (System.out, "UTF8");
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File(argv [0]), new Echo() );
}
catch (Throwable t)
{
t.printStackTrace ();
}
System.exit (0);
}
public void startDocument() throws SAXException
{
nl();
nl();
emit ("START DOCUMENT");
nl();
emit ("<?xml version='1.0' encoding='UTF-8'?>");
}
public void endDocument () throws SAXException
{
nl();
emit ("END DOCUMENT");
try
{
nl();
out.flush ();
}
catch (IOException e)
{
throw new SAXException ("I/O error", e);
}
}
public void startElement (String name, AttributeList attrs)
throws SAXException
{
indentLevel++;
nl();
emit ("ELEMENT: ");
emit ("<"+name);
if (attrs != null)
{
for (int i = 0; i < attrs.getLength (); i++)
{
nl();
emit(" ATTR: ");
emit (attrs.getName (i));
emit ("\t\"");
emit (attrs.getValue (i));
emit ("\"");
}
}
if (attrs.getLength() > 0) nl();
emit (">");
}
public void endElement (String name) throws SAXException
{
nl();
emit ("END_ELM: ");
emit (""+name+">");
indentLevel--;
}
public void characters (char buf [], int offset, int len)
throws SAXException
{
nl();
emit ("CHARS: ");
String s = new String(buf, offset, len);
if (!s.trim().equals("")) emit (s);
}
private void emit (String s) throws SAXException
{
try
{
out.write (s);
out.flush ();
}
catch (IOException e)
{
throw new SAXException ("I/O error", e);
}
}
private void nl () throws SAXException
{
String lineEnd = System.getProperty("line.separator");
try
{
out.write (lineEnd);
for (int i=0; i < indentLevel; i++)
out.write(indentString);
}
catch (IOException e)
{
throw new SAXException ("I/O error", e);
}
}
}
//
// Vereinfachte Version des o.g. Parsers: Handler-Klasse separat
// erfordert Handler.class
// zeigt das Sax-Parsen von XML- und HTML-Dokumenten
// die Tags und Inhalte werden angezeigt
//
// umgebaut 9.7.00 AG
import java.io.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
public class Sax2
{
public static void main (String argv[])
{
if (argv.length != 1)
{
System.err.println ("Usage: cmd filename");
System.exit (1);
}
try
{
SAXParser saxParser =
SAXParserFactory.newInstance().newSAXParser();
saxParser.parse( new File(argv [0]), new Handler() );
}
catch (Throwable t)
{
t.printStackTrace ();
}
System.exit (0);
}
}
//Handler fuer den SaxParser Sax2.class
//
// bringt nur Tags und Inhalte aber keine Attribute(?)
// 9.7.00 AG
import org.xml.sax.HandlerBase;
import org.xml.sax.SAXException;
import org.xml.sax.AttributeList;
public class Handler extends HandlerBase
{
public void startDocument()
{
System.out.println("BEGINN DOKUMENT\n");
}
public void endDocument ()
{
System.out.println("\nENDE DOKUMENT");
}
public void startElement (String name, AttributeList attrs)
{
System.out.print("<"+name+">");
}
public void endElement (String name)
{
System.out.println(""+name+">");
}
public void characters (char buf [], int offset, int len)
{
String s = new String(buf, offset, len);
System.out.print(s);
}
}
// Handler fuer den SaxParser SonettSax.class
// zur Ausgabe von Sonetten in XML-Dateien
//
// unterscheidet anhand eines Attributs verschiedene Sonett-Typen
// und macht entsprechende Zeilenumbrueche
// 14.7.00 AG
import org.xml.sax.HandlerBase;
import org.xml.sax.SAXException;
import org.xml.sax.AttributeList;
public class SonettHandler extends HandlerBase
{
String Sonnettyp = null;
boolean ausgeben = false;
int zeilen[][] = {{4,3,2,1, 4,3,2,1, 4,3,2,1, 2,1},
{4,3,2,1, 4,3,2,1, 3,2,1, 3,2,1}};
int t = 1;
int i = 0;
public void startDocument()
{
System.out.println();
}
public void endDocument ()
{
}
public void startElement (String name, AttributeList attrs)
{
if( name.equals("sonnet"))
{
Sonnettyp = attrs.getValue("type");
if( Sonnettyp.equals("Shakespearean"))
t = 0;
}
if( name.equals("line"))
ausgeben = true;
if( name.equals("/line"))
ausgeben = false;
}
public void endElement (String name)
{
if( name.equals("line"))
{
int z = zeilen[t][i];
if( z == 1 )
System.out.println( "\n");
i++;
}
}
public void characters (char buf [], int offset, int len)
{
if( ausgeben == true )
{
String s = new String(buf, offset, len);
System.out.print(s);
}
}
}
//---------------------------------------------------------------------------||
// xmlfromdom.java ||
// ||
// This code generates an XML document from a portion of a DOM tree. ||
//---------------------------------------------------------------------------||
// Written 17 February 2000 by Doug Tidwell. ||
//---------------------------------------------------------------------------||
// ||
// (C) Copyright IBM Corp. 1999, 2000. All rights reserved. ||
// ||
// US Government Users Restricted Rights Use, duplication or ||
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp. ||
// ||
// The program is provided "as is" without any warranty express or ||
// ll not be liable for any third party claims against you. ||
//
// siehe: http://www.ibm.com/software/developer/library/servlets-and-xml/ ||
//-----umgebaut 7.7.00 AG----------------------------------------------------||
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class xmlfromdom extends HttpServlet
{
Document doc = null;
Element author = null;
Element lines = null;
Element title = null;
public void initialize()
{
DocumentBuilderFactory docBFac;
DocumentBuilder docBuild;
try
{
docBFac = DocumentBuilderFactory.newInstance();
docBuild = docBFac.newDocumentBuilder();
doc = docBuild.newDocument();
}
catch( Exception e )
{}
if (doc != null)
{
Element root = doc.createElement("sonnet");
root.setAttribute("type", "Shakespearean");
author = doc.createElement("author");
Element lastName = doc.createElement("last-name");
lastName.appendChild(doc.createTextNode("Shakespeare"));
author.appendChild(lastName);
Element firstName = doc.createElement("first-name");
firstName.appendChild(doc.createTextNode("William"));
author.appendChild(firstName);
Element nationality = doc.createElement("nationality");
nationality.appendChild(doc.createTextNode("British"));
author.appendChild(nationality);
Element yearOfBirth = doc.createElement("year-of-birth");
yearOfBirth.appendChild(doc.createTextNode("1564"));
author.appendChild(yearOfBirth);
Element yearOfDeath = doc.createElement("year-of-death");
yearOfDeath.appendChild(doc.createTextNode("1616"));
author.appendChild(yearOfDeath);
root.appendChild(author);
title = doc.createElement("title");
title.appendChild(doc.createTextNode("Sonnet 130"));
root.appendChild(title);
lines = doc.createElement("lines");
Element line01 = doc.createElement("line");
line01.appendChild(doc.createTextNode("My mistress' eyes are nothing like the sun,"));
lines.appendChild(line01);
Element line02 = doc.createElement("line");
line02.appendChild(doc.createTextNode("Coral is far more red than her lips red."));
lines.appendChild(line02);
Element line03 = doc.createElement("line");
line03.appendChild(doc.createTextNode("If snow be white, why then her breasts are dun,"));
lines.appendChild(line03);
Element line04 = doc.createElement("line");
line04.appendChild(doc.createTextNode("If hairs be wires, black wires grow on her head."));
lines.appendChild(line04);
Element line05 = doc.createElement("line");
line05.appendChild(doc.createTextNode("I have seen roses damasked, red and white,"));
lines.appendChild(line05);
Element line06 = doc.createElement("line");
line06.appendChild(doc.createTextNode("But no such roses see I in her cheeks."));
lines.appendChild(line06);
Element line07 = doc.createElement("line");
line07.appendChild(doc.createTextNode("And in some perfumes is there more delight"));
lines.appendChild(line07);
Element line08 = doc.createElement("line");
line08.appendChild(doc.createTextNode("Than in the breath that from my mistress reeks."));
lines.appendChild(line08);
Element line09 = doc.createElement("line");
line09.appendChild(doc.createTextNode("I love to hear her speak, yet well I know"));
lines.appendChild(line09);
Element line10 = doc.createElement("line");
line10.appendChild(doc.createTextNode("That music hath a far more pleasing sound."));
lines.appendChild(line10);
Element line11 = doc.createElement("line");
line11.appendChild(doc.createTextNode("I grant I never saw a goddess go,"));
lines.appendChild(line11);
Element line12 = doc.createElement("line");
line12.appendChild(doc.createTextNode("My mistress when she walks, treads on the ground."));
lines.appendChild(line12);
Element line13 = doc.createElement("line");
line13.appendChild(doc.createTextNode("And yet, by Heaven, I think my love as rare"));
lines.appendChild(line13);
Element line14 = doc.createElement("line");
line14.appendChild(doc.createTextNode("As any she belied with false compare."));
lines.appendChild(line14);
root.appendChild(lines);
doc.appendChild(root);
}
}
/** Prints the specified node, recursively. */
public void printDOMTree(Node node, PrintWriter out)
{
int type = node.getNodeType();
switch (type)
{
// print the document element
case Node.DOCUMENT_NODE:
{
printDOMTree(((Document)node).getDocumentElement(), out);
break;
}
// print element with attributes
case Node.ELEMENT_NODE:
{
out.print("<");
out.print(node.getNodeName());
NamedNodeMap attrs = node.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node attr = attrs.item(i);
out.print(" " + attr.getNodeName() +
"=\"" + attr.getNodeValue() +
"\"");
}
out.print(">");
NodeList children = node.getChildNodes();
if (children != null)
{
int len = children.getLength();
for (int i = 0; i < len; i++)
printDOMTree(children.item(i), out);
}
break;
}
// handle entity reference nodes
case Node.ENTITY_REFERENCE_NODE:
{
out.print("&");
out.print(node.getNodeName());
out.print(";");
break;
}
// print cdata sections
case Node.CDATA_SECTION_NODE:
{
out.print("<![CDATA[");
out.print(node.getNodeValue());
out.print("]]>");
break;
}
// print text
case Node.TEXT_NODE:
{
out.print(node.getNodeValue());
break;
}
// print processing instruction
case Node.PROCESSING_INSTRUCTION_NODE:
{
out.print("<?");
out.print(node.getNodeName());
String data = node.getNodeValue();
{
out.print(" ");
out.print(data);
}
out.print("?>");
break;
}
}
if (type == Node.ELEMENT_NODE)
{
out.print("</");
out.print(node.getNodeName());
out.print('>');
}
} // printDOMTree(Node, PrintWriter)
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
if (doc == null)
initialize();
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
out.println("<?xml version=\"1.0\" ?>");
printDOMTree(doc, out);
}
}