Parser = Programm zum Einlesen von Dokumenten entsprechend einer Syntax-Definition. Das Ergebnis ist eine interne Datenstruktur.
Lexikalische Analyse: Scanner
z.B. LEX
Syntaktische Analyse:
z.B YACC oder GNU BISON,
bei XML Wohlgeformtheit feststellen
Semantische Analyse:
auch YACC / BISON,
bei XML Gültigkeit bez. DTD feststellen
Ausblick:
Java API for XML Binding (JAXM)
Generation der Java Klassen direkt aus einer DTD.
DOM = Document Object Model, W3C
erzeugt (Java-)Objekt aus XML Datei, erlaubt Manipulation dieser Objekte
DocumentBuilder
DocumentBuilderFactory
SAX = Simple API for XML, XML-Developer
Ereignisse (wie startElement) werden durch Handler verarbeitet
SAXParser
SAXParserFactory
SAX 2 mit Namespace Unterstützung
Vorteile:
DOM liefert fertiges Dokumenten Objekt
SAX ist sehr effizient und braucht wenig Speicher
Nachteile:
DOM ist ineffizient und braucht viel Speicher
bei DOM muss evtl. die Datenstruktur doppelt erzeugt werden
bei SAX keine Garantie, dass gültige Dokumente entstehen
Entwicklung der SAX Handler für komplizierte DTDs schwer
Apache Xerces: org.apache.xerces.parser.DOMParser
im JDK ab 1.4 als: javax.xml.parsers.DocumentBuilder
und javax.xml.parsers.DocumentBuilderFactory
javax.xml.parsers.DocumentBuilderFactory
dient der Erzeugung
eines DOM Parsers javax.xml.parsers.DocumentBuilder
.
protected DocumentBuilderFactory() public static newInstance() public DocumentBuilder newDocumentBuilder() public boolean isValidating() public void setValidating(boolean) public boolean isExpandEntityReferences() public void setExpandEntityReferences(boolean)
javax.xml.parsers.DocumentBuilder
dient dem Parsen,
d.h. dem Einlesen und Aufbau eines org.w3c.dom.Document
.
protected DocumentBuilder() public Document newDocument() public Document parse(File f) public Document parse(InputStream is) public Document parse(InputSource is) public Document parse(String uri) public boolean isValidating() public void setErrorHandler(ErrorHandler)
DOMLeser:
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.IOException; import org.xml.sax.SAXException; public class DOMLeser { public static void main(String[] args) { DocumentBuilderFactory pfac = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = null; try { pfac.setValidating(true); // pfac.setCoalescing(true); pfac.setExpandEntityReferences(false); parser = pfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document doc = null; String uri = "datei.xml"; try { doc = parser.parse(uri); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Screen sc = new Screen(); sc.println("doc("+ doc.getClass().getName() + ") = " + doc ); DOMSchreiber dw = new DOMSchreiber(); sc.println("document:\n"); dw.printNode(doc); dw.flush(); dw.close(); } }
Die Werte von nodeName
, nodeValue
,
und attributes
hängen wie folgt vom Knotentyp ab:
Interface | nodeName | nodeValue | attributes |
---|---|---|---|
Attr | name of attribute | value of attribute | null |
CDATASection | "#cdata-section" |
content of the CDATA Section | null |
Comment | "#comment" |
content of the comment | null |
Document | "#document" |
null | null |
DocumentFragment |
"#document-fragment" |
null | null |
DocumentType | document type name | null | null |
Element | tag name | null | NamedNodeMap |
Entity | entity name | null | null |
EntityReference | name of entity referenced | null | null |
Notation | notation name | null | null |
ProcessingInstruction | target | entire content excluding the target | null |
Text |
"#text" |
content of the text node | null |
Siehe Document Object Model (DOM) Level 2 Core Specification.
DOMUtil:
import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Element; public class DOMUtil { private static int inc = 0; public static void addIdent(Node node, String prefix) { switch ( node.getNodeType() ) { case Node.ELEMENT_NODE: addElementIdent( (Element)node, prefix ); break; case Node.DOCUMENT_NODE: addElementIdent( ((Document)node).getDocumentElement(), prefix ); break; default: ; } } public static void addElementIdent(Element el, String prefix) { el.setAttribute("id", "#"+prefix+inc); el.setAttribute("name", "#"+prefix+inc++); NodeList nl = el.getChildNodes(); if ( ( nl == null ) || ( nl.getLength() == 0 ) ) { return; } for (int i = 0; i < nl.getLength(); i++ ){ Node c = nl.item(i); addIdent(c, prefix); } } }
Anwendung:
// ... wie oben DOMUtil.addIdent(doc,"hk"); sc.println("document:\n"); dw.printNode(doc); dw.flush(); sc.println();
Ausgabe:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd" > <html id="#hk0" name="#hk0" xmlns="http://www.w3.org/1999/xhtml"> <head id="#hk1" name="#hk1"> <title id="#hk2" name="#hk2">Titel</title> <?php $a=9; function yyy(a) { if ( a > 2 ) { print("<p>nonsense</p>"); } } ?> <!-- funktions definitionen --> <script id="#hk3" language="JavaScript" name="#hk3" type="text/javascript"> <![CDATA[ ]]> </script> </head> <body bgcolor="white" id="#hk4" name="#hk4"> <h1 id="#hk5" name="#hk5">Überschrift A</h1> <p align="center" id="#hk6" name="#hk6">Paragraph mit <em id="#hk7" name="#hk7">Hervorhebung</em> und einem <br clear="none" id="#hk8" name="#hk8" /> Zeilenumbruch. </p> <ul id="#hk9" name="#hk9"> <li id="#hk10" name="#hk10">Listen Element</li> <li id="#hk11" name="#hk11">Entity Element &abc; </li> </ul> <h1 id="#hk12" name="#hk12">Überschrift B</h1> <p id="#hk13" name="#hk13">Text eines zweiten Paragraphen mit <strong id="#hk14" name="#hk14">Hervorhebung</strong> ohne Zeilenumbruch. </p> <h1 count="10" id="#hk15" name="#hk15">Überschrift C</h1> <p id="#hk16" name="#hk16">Text eines dritten Paragraphen ohne Hervorhebungen und ohne Zeilenumbruch. </p> <h1 id="#hk17" name="#hk17">Überschrift D</h1> <p id="#hk18" name="#hk18">Text eines vierten Paragraphen ohne Hervorhebungen und ohne Zeilenumbruch. </p> </body> </html>
Apache Xerces: org.apache.xerces.parser.SAXParser
im JDK ab 1.4 als: javax.xml.parsers.SAXParser
und javax.xml.parsers.SAXParserFactory
javax.xml.parsers.SAXParserFactory
dient der Erzeugung
eines SAX Parsers javax.xml.parsers.SAXParser
.
protected SAXParserFactory() public static newInstance() public SAXParser newSAXParser() boolean isValidating() void setValidating(boolean) boolean isExpandEntityReferences() void setExpandEntityReferences(boolean) boolean isNamespaceAware() void setNamespaceAware(boolean)
javax.xml.parsers.SAXParser
dient dem Parsen,
d.h. dem Einlesen und Verarbeiten der gefundenen XML Konstrukte.
protected SAXParser() public void parse(File f, DefaultHandler dh) public void parse(InputStream is, DefaultHandler dh) public void parse(InputSource is, DefaultHandler dh) public void parse(String uri, DefaultHandler dh) public boolean isValidating() public abstract void setProperty(String name, Object value) public abstract Object getProperty(String name)
SAXLeser:
import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXLeser { public static void main(String[] args) { SAXParserFactory pfac = SAXParserFactory.newInstance(); SAXParser parser = null; try { pfac.setValidating(true); pfac.setNamespaceAware(true); parser = pfac.newSAXParser(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } Screen sc = new Screen(); String uri = "datei.xhtml"; DefaultHandler dh = new SAXSchreiber(sc); try { parser.parse(uri,dh); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
DefaultHandler aus
org.xml.sax.helpers
,
implementiert die Interfaces
ContentHandler, DTDHandler, EntityResolver und ErrorHandler:
public void startDocument() public void endDocument() public void startElement(String nameuri, String local, String quali, Attributes attrs) public void endElement(String nameuri, String local, String quali) public void characters(char ch[], int start, int length) public void ignorableWhitespace(char ch[], int start, int length) public void processingInstruction(String target, String data) public void warning(SAXParseException ex) public void error(SAXParseException ex) public void fatalError(SAXParseException ex) public InputSource resolveEntity(String publicId, String systemId) public void notationDecl(String name, String publicId, String systemId)
SAXSchreiber:
import java.io.IOException; import java.io.PrintWriter; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.helpers.DefaultHandler; public class SAXSchreiber extends DefaultHandler { PrintWriter pw = null; public SAXSchreiber() { pw = new Screen(); } public SAXSchreiber(PrintWriter p) { pw = p; } public void startDocument() { pw.println("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"); pw.flush(); } public void endDocument() { pw.println(); pw.flush(); } public void startElement(String nameuri, String local, String quali, Attributes attrs) { pw.print('<'); pw.print(local); if (attrs != null) { int len = attrs.getLength(); for (int i = 0; i < len; i++) { pw.print(' '); pw.print(attrs.getQName(i)); pw.print("=\""); pw.print(attrs.getValue(i)); pw.print('"'); } } pw.print('>'); pw.flush(); } public void endElement(String nameuri, String local, String quali) { pw.print("</"); pw.print(local); pw.print('>'); pw.flush(); } public void characters(char ch[], int start, int length) { pw.print( new String(ch, start, length) ); pw.flush(); } public void ignorableWhitespace(char ch[], int start, int length) { characters(ch, start, length); } public void processingInstruction(String target, String data) { pw.print("<?"); pw.print(target); if (data != null && data.length() > 0) { pw.print(' '); pw.print(data); } pw.print("?>"); pw.flush(); } public void warning(SAXParseException ex) { pw.println("\n<!-- [Warning] "+ ex.getSystemId()+": line "+ ex.getLineNumber()+", column "+ ex.getColumnNumber()+":\n"+ ex.getMessage() + " -->"); } public void error(SAXParseException ex) { pw.println("\n<!-- [Error] "+ ex.getSystemId()+": line "+ ex.getLineNumber()+", column "+ ex.getColumnNumber()+":\n"+ ex.getMessage() + " -->"); } public void fatalError(SAXParseException ex) { pw.println("\n<!-- [Fatal Error] "+ ex.getSystemId()+": line "+ ex.getLineNumber()+", column "+ ex.getColumnNumber()+":\n"+ ex.getMessage() + " -->"); } public InputSource resolveEntity(String publicId, String systemId) { pw.println("\n<!-- [resolveEntity] publicId: "+ publicId + ", systemId: " + systemId + " -->" ); boolean dtd = false; boolean pid = false; boolean sid = false; if ( ( publicId != null ) || ( systemId != null ) ) { pid = pid || ( publicId.indexOf("DTD") >= 0 ); pid = pid || ( publicId.indexOf("dtd") >= 0 ); sid = sid || ( systemId.indexOf("DTD") >= 0 ); sid = sid || ( systemId.indexOf("dtd") >= 0 ); } if (pid) { pw.print("<!DOCTYPE ???? " ); pw.print("PUBLIC \"" + publicId + "\""); if (sid) { pw.print(" \"" + systemId + "\""); pw.println(" >"); } } else if (sid) { pw.print("<!DOCTYPE ???? " ); pw.print("SYSTEM \"" + systemId + "\""); pw.println(" >"); } return null; } public void notationDecl(String name, String publicId, String systemId) { pw.println("\n[notationDeclaration] name: " + name + " publicId: "+ publicId + ", systemId: " + systemId ); } }
Attributes aus org.xml.sax
,
AttributesImpl aus org.xml.sax.helpers
:
interface Attributes
int getLength() int getIndex(String qName) int getIndex(String uri, String localName) String getQName(int index) String getLocalName(int index) String getURI(int index) String getValue(int index) String getValue(String qName) String getValue(String uri, String localName) String getType(int index) String getType(String qName) String getType(String uri, String localName)
class AttributesImpl plus
AttributesImpl() AttributesImpl(Attributes atts) void clear() void removeAttribute(int index) void addAttribute(String uri, String localName, String qName, String type, String value) void addAttribute(int index, String uri, String localName, String qName, String type, String value) void setAttributes(Attributes atts) void setLocalName(int index, String localName) void setQName(int index, String qName) void setType(int index, String type) void setURI(int index, String uri) void setValue(int index, String value)
SAXUtil: Nummerieren der h1-Überschriften
import java.io.IOException; import java.io.PrintWriter; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.AttributesImpl; public class SAXUtil extends SAXSchreiber { int chapter = 0; boolean insertCounter = false; public SAXUtil() { pw = new Screen(); } public SAXUtil(PrintWriter p) { pw = p; } public void startDocument() { chapter = 0; super.startDocument(); } public void startElement(String nameuri, String local, String quali, Attributes attrs) { if ( !quali.equals("h1") ) { super.startElement(nameuri,local,quali,attrs); pw.flush(); return; } Attributes at = attrs; String cVal = null; if ( at != null ) { cVal = at.getValue("count"); if (cVal == null) { cVal = "" + (++chapter); AttributesImpl ai = new AttributesImpl(at); ai.addAttribute("","","count","",cVal); at = (Attributes) ai; } else { chapter = Integer.parseInt(cVal); } } else { AttributesImpl ai = new AttributesImpl(); cVal = "" + (++chapter); ai.addAttribute("","","count","",cVal); at = (Attributes) ai; } insertCounter = true; super.startElement(nameuri,local,quali,at); } public void characters(char ch[], int start, int length) { String s = new String(ch, start, length); if ( insertCounter ) { s = "Kapitel " + chapter + ". " + s; insertCounter = false; } pw.print( s ); pw.flush(); } public InputSource resolveEntity(String publicId, String systemId) { return null; } public void notationDecl(String name, String publicId, String systemId) { } }
Ausgabe für datei.xhtml von oben:
Ist in Java 5.0 enthalten
Support für XML Schema und Validierung
Support für RelaxNG (möglich)
Support für XPath
DOM Level 3 Load und Store
Support für XInclude
Funktioniert wie bisher durch Setzen von
domfactory.setValidating(true)
.
static boolean validateDTD(String[] files) { DocumentBuilderFactory pfac = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = null; MyErrorHandler eh = new MyErrorHandler(); try { pfac.setValidating(true); pfac.setNamespaceAware(true); pfac.setXIncludeAware(true); parser = pfac.newDocumentBuilder(); parser.setErrorHandler( eh ); } catch (ParserConfigurationException e) { e.printStackTrace(); return false; } boolean valid = true; File xmlFile; for ( int i = 0; i < files.length; i++ ) { xmlFile = new File( files[i] ); valid &= validateDTD( eh, parser, xmlFile ); eh.reset(); } return valid; }
static boolean validateDTD(MyErrorHandler eh, DocumentBuilder parser, File file) { Document document = null; try { document = parser.parse( file ); } catch (SAXException e) { System.out.println(file.getName() + " not valid" ); e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } if ( eh.errors() > 0 || eh.fatalErrors() > 0 ) { System.out.println(file.getName() + " not valid, " + eh ); return false; } else if ( eh.warnings() > 0 ) { System.out.println(file.getName() + " is valid, " + eh ); return true; } else { System.out.println(file.getName() + " is valid" ); return true; } }
Beispiel für die Validierung der Verlesungsunterlagen:
java Validation DOCTYPE ../*.html ende.html is valid index.html is valid ... sess-503.html is valid start.html is valid title.html is valid
class MyErrorHandler extends DefaultHandler implements ErrorHandler { int errors = 0; int fatalErrors = 0; int warnings = 0; public void reset() { errors = 0; fatalErrors = 0; warnings = 0; } public void error(SAXParseException exception) { System.out.print("Error: "); errors++; message(exception); } public void fatalError(SAXParseException exception) { System.out.print("FatalError: "); fatalErrors++; message(exception); } public void warning(SAXParseException exception) { System.out.print("Warning: "); warnings++; message(exception); } void message(SAXParseException exception) { if ( exception.getSystemId() != null ) { System.out.print(exception.getSystemId()); System.out.println(", line " + exception.getLineNumber()); } System.out.println( exception.getMessage() ); } public String toString() { return counters(); } public String counters() { StringBuffer s = new StringBuffer(); s.append(warnings + " warnings, "); s.append(errors + " errors, "); s.append(fatalErrors + " fatalErrors"); return s.toString(); } }
neues Paket javax.xml.validation
mit den Klassen Schema
,
SchemaFactory
und Validator
Erzeugung mit
SchemaFactory.newInstance(..)
Schema aus Datei initialisieren
factory.newSchema( schemaSource )
neuer Validierer schema.newValidator()
Setzen der Fehlerbehandlung
validator.setErrorHandler( eh )
Validieren einer Datei (aus einer DOM Quelle)
validator.validate( domSource )
static boolean validateSchema(String sfile, String[] files) { File schemaFile = new File( sfile ); StreamSource schemaSource = new StreamSource( schemaFile ); SchemaFactory sfac = SchemaFactory.newInstance( // XMLConstants.XML_DTD_NS_URI XMLConstants.W3C_XML_SCHEMA_NS_URI // XMLConstants.RELAXNG_NS_URI ); Schema schema = null; try { schema = sfac.newSchema( schemaSource ); } catch (SAXException e) { e.printStackTrace(); return false; } Validator validator = schema.newValidator(); MyErrorHandler eh = new MyErrorHandler(); validator.setErrorHandler( eh ); DocumentBuilderFactory pfac = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = null; try { pfac.setNamespaceAware(true); pfac.setXIncludeAware(true); parser = pfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); return false; } boolean valid = true; File xmlFile; for ( int i = 0; i < files.length; i++ ) { xmlFile = new File( files[i] ); valid &= validateSchema( eh, validator, parser, xmlFile ); eh.reset(); } return valid; }
static boolean validateSchema(MyErrorHandler eh, Validator validator, DocumentBuilder parser, File xmlFile) { DOMSource domSource = null; try { Document document = null; document = parser.parse( xmlFile ); domSource = new DOMSource(document); } catch (SAXException e) { e.printStackTrace(); return false; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } try { validator.validate( domSource ); } catch (SAXException e) { return false; } catch (IOException e) { e.printStackTrace(); return false; } if ( eh.errors() > 0 || eh.fatalErrors() > 0 ) { System.out.println(xmlFile.getName() + " not valid, " + eh ); return false; } else if ( eh.warnings() > 0 ) { System.out.println(xmlFile.getName() + " is valid, " + eh ); return true; } else { System.out.println(xmlFile.getName() + " is valid" ); return true; } }
Beispiel für die Validierung der Schema Beispiele:
java Validation "SCHEMA(schema/Bestellung-1.xsd)" schema/Bestellung-*.xsi schema file = schema/Bestellung-1.xsd Bestellung-1.xsi is valid Error: http://www.w3.org/TR/xml-schema-1#cvc-datatype-valid.1.2.1?D-68131&integer Error: http://www.w3.org/TR/xml-schema-1#cvc-type.3.1.3?plz&D-68131 Error: http://www.w3.org/TR/xml-schema-1#cvc-datatype-valid.1.2.1?zwei&integer Error: http://www.w3.org/TR/xml-schema-1#cvc-type.3.1.3?anzahl&zwei Bestellung-1e.xsi not valid, 0 warnings, 4 errors, 0 fatalErrors Error: http://www.w3.org/TR/xml-schema-1#cvc-datatype-valid.1.2.1?DM 22&decimal Error: http://www.w3.org/TR/xml-schema-1#cvc-type.3.1.3?preis&DM 22 Bestellung-2e.xsi not valid, 0 warnings, 2 errors, 0 fatalErrors Bestellung-3e.xsi is valid Error: http://www.w3.org/TR/xml-schema-1#cvc-type.3.1.1?bemerkung&priority Bestellung-4.xsi not valid, 0 warnings, 1 errors, 0 fatalErrors Error: http://www.w3.org/TR/xml-schema-1#cvc-type.3.1.1?bemerkung&priority Bestellung-4e.xsi not valid, 0 warnings, 1 errors, 0 fatalErrors
Datei Validation.java
neues Paket javax.xml.xpath
u.A. mit den Klassen XPath
,
XPathFactory
und XPathExpression
Erzeugung mit
XPathFactory.newInstance()
XPath initialisieren
factory.newXPath()
Ausdruck evtuell kompilieren
xpath.compile("xpath-expr")
Ausführen der Selection
evaluate(document,NODESET)
bzw.
evaluate("xpath-expr",document,NODESET)
Weiterverarbeiten der DOM
NodeList
static void select(String xpath, String[] files) { DocumentBuilderFactory pfac = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = null; try { parser = pfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); return; } DOMImplementation dimp = parser.getDOMImplementation(); DOMImplementationLS dimpls = null; LSSerializer store = null; if ( dimp.hasFeature("LS","3.0") ) { dimpls = (DOMImplementationLS) dimp; store = dimpls.createLSSerializer(); DOMConfiguration conf = store.getDomConfig(); conf.setParameter("xml-declaration",false); } XPathFactory xfac = XPathFactory.newInstance(); XPath xp = xfac.newXPath(); XPathExpression expression = null; try { expression = xp.compile(xpath); } catch (XPathExpressionException e) { e.printStackTrace(); return; } boolean valid = true; File xmlFile; NodeList nl; StringBuffer res = new StringBuffer("\n"); for ( int i = 0; i < files.length; i++ ) { xmlFile = new File( files[i] ); res.append( select( expression, parser, xmlFile, store ) ); } //System.out.println( store.writeToString(result) ); System.out.println( res.toString() ); return; }
neues Paket org.w3c.dom.ls
u.A. mit den Klassen LSSerializer
,
LSParser
und
DOMImplementationLS
Erzeugung oder Zugriff auf eine DOM Implementierung
domparser.getDOMImplementation()
Test ob LS unterstützt wird
impl.hasFeature("LS","3.0")
wenn ja, casten auf
DOMImplementationLS
Erzeugen eines Serializers
impl.createLSSerializer()
oder eines Parsers
impl.createLSParser(mode,schema)
Ausgabe eines Nodes
serializer.write(node,output)
bzw. Konversion zu String
serializer.writeToString(node)
Lesen eines Dokuments
parser.parse(input)
static String select(XPathExpression expression, DocumentBuilder parser, File file, LSSerializer store) { Document document = null; System.out.println("file = " + file.getName()); try { document = parser.parse( file ); } catch (SAXException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } NodeList nl = null; try { nl = (NodeList)expression.evaluate(document,XPathConstants.NODESET); } catch (XPathExpressionException e) { e.printStackTrace(); return null; } //System.out.println("hits = " + nl.getLength() ); StringBuffer nls = new StringBuffer(); for ( int i = 0; i < nl.getLength(); i++ ) { Node n = nl.item(i); if ( n != null ) { if ( store != null ) { nls.append( store.writeToString(n) + "\n" ); } else { nls.append( n.getTextContent() + "\n" ); } } } //System.out.println(nls.toString()); return nls.toString(); }
Beispiel für den Ausdruck "//h1
"
java XPathGrep "//h1" datei.xhtml expression = //h1 file = datei.xhtml <h1>Überschrift A</h1> <h1>Überschrift B</h1> <h1 count="10">Überschrift C</h1> <h1>Überschrift D</h1>
Datei XPathGrep.java
W3C Recommendation, 20. December 2004
zusätzliche Funktionalität der DOM und SAX Parser, die über die entsprechende Factory aktiviert wird
factory.setXIncludeAware(true)
evtl. noch mit
factory.setNamespaceAware(true)
Anwendung in einer XML Datei:
<?xml version="1.0" ... ?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:xi="http://www.w3.org/2001/XInclude" > ... <xi:include href="datei.xhtml" parse="xml" > <xi:fallback>File not found</xi:fallback> </xi:include> ... <xi:include href="datei.txt" parse="text" /> ... </html>
© Universität Mannheim, Rechenzentrum, 1998-2006.
Heinz KredelLast modified: Sun May 28 22:10:26 CEST 2006