Commit 50fe9bb2 authored by Administrator's avatar Administrator

Initial commit

parents
/target/
.classpath
.settings
.project
This diff is collapsed.
# Ejemplos de APIs para XML
Ejemplos de APIs para XML incluidos en el Tema 5.5 de la asignatura DAI.
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="libros.xsl"?>
<libros xmlns="http://www.esei.uvigo.es/dai/libros"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<libro titulo="XML">
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">XML Bien Formado</capitulo>
<capitulo numero="3">Validación</capitulo>
<capitulo numero="4">APIs</capitulo>
<capitulo numero="5">XPath y XSLT</capitulo>
</libro>
<libro>
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">Etiquetas HTML</capitulo>
<capitulo numero="3">Estilos CSS</capitulo>
<capitulo numero="4">Árbol DOM</capitulo>
<capitulo numero="5">JavaScript</capitulo>
</libro>
</libros>
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT libros (libro+)>
<!ELEMENT libro (capitulo+)>
<!ATTLIST libro titulo CDATA #REQUIRED>
<!ELEMENT capitulo (#PCDATA)>
<!ATTLIST capitulo numero CDATA #REQUIRED>
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="libros.xsl"?>
<!DOCTYPE libros SYSTEM "libros.dtd" >
<libros>
<libro titulo="XML">
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">XML Bien Formado</capitulo>
<capitulo numero="3">Validación</capitulo>
<capitulo numero="4">APIs</capitulo>
<capitulo numero="5">XPath y XSLT</capitulo>
</libro>
<libro>
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">Etiquetas HTML</capitulo>
<capitulo numero="3">Estilos CSS</capitulo>
<capitulo numero="4">Árbol DOM</capitulo>
<capitulo numero="5">JavaScript</capitulo>
</libro>
</libros>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE libros SYSTEM "libros.dtd" >
<libros>
<libro titulo="XML">
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">XML Bien Formado</capitulo>
<capitulo numero="3">Validación</capitulo>
<capitulo numero="4">APIs</capitulo>
<capitulo numero="5">XPath y XSLT</capitulo>
</libro>
<libro titulo="HTML">
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">Etiquetas HTML</capitulo>
<capitulo numero="3">Estilos CSS</capitulo>
<capitulo numero="4">Árbol DOM</capitulo>
<capitulo numero="5">JavaScript</capitulo>
</libro>
</libros>
<!DOCTYPE html><html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Libros</title>
</head>
<body>
<h1>Lista de Libros</h1>
<div>
<h2>XML</h2>
<ol>
<li>Introducci&oacute;n</li>
<li>XML Bien Formado</li>
<li>Validaci&oacute;n</li>
<li>APIs</li>
<li>XPath y XSLT</li>
</ol>
</div>
<div>
<h2>HTML</h2>
<ol>
<li>Introducci&oacute;n</li>
<li>Etiquetas HTML</li>
<li>Estilos CSS</li>
<li>&Aacute;rbol DOM</li>
<li>JavaScript</li>
</ol>
</div>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="libros.xsl"?>
<libros xmlns="http://www.esei.uvigo.es/dai/libros"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<libro titulo="XML">
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">XML Bien Formado</capitulo>
<capitulo numero="3">Validación</capitulo>
<capitulo numero="4">APIs</capitulo>
<capitulo numero="5">XPath y XSLT</capitulo>
</libro>
<libro titulo="HTML">
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">Etiquetas HTML</capitulo>
<capitulo numero="3">Estilos CSS</capitulo>
<capitulo numero="4">Árbol DOM</capitulo>
<capitulo numero="5">JavaScript</capitulo>
</libro>
</libros>
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.esei.uvigo.es/dai/libros"
xmlns:tns="http://www.esei.uvigo.es/dai/libros"
elementFormDefault="qualified">
<complexType name="capitulo">
<simpleContent>
<extension base="string">
<attribute name="numero" type="unsignedInt" use="required"/>
</extension>
</simpleContent>
</complexType>
<complexType name="libro">
<sequence>
<element name="capitulo" type="tns:capitulo" maxOccurs="unbounded"/>
</sequence>
<attribute name="titulo" type="string" use="required"/>
</complexType>
<element name="libros">
<complexType>
<sequence>
<element name="libro" type="tns:libro" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
</schema>
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="libros.xsl"?>
<libros xmlns="http://www.esei.uvigo.es/dai/libros"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.esei.uvigo.es/dai/libros libros.xsd ">
<libro titulo="XML">
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">XML Bien Formado</capitulo>
<capitulo numero="3">Validación</capitulo>
<capitulo numero="4">APIs</capitulo>
<capitulo numero="5">XPath y XSLT</capitulo>
</libro>
<libro>
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">Etiquetas HTML</capitulo>
<capitulo numero="3">Estilos CSS</capitulo>
<capitulo numero="4">Árbol DOM</capitulo>
<capitulo numero="5">JavaScript</capitulo>
</libro>
</libros>
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="libros.xsl"?>
<libros xmlns="http://www.esei.uvigo.es/dai/libros"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.esei.uvigo.es/dai/libros libros.xsd ">
<libro titulo="XML">
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">XML Bien Formado</capitulo>
<capitulo numero="3">Validación</capitulo>
<capitulo numero="4">APIs</capitulo>
<capitulo numero="5">XPath y XSLT</capitulo>
</libro>
<libro titulo="HTML">
<capitulo numero="1">Introducción</capitulo>
<capitulo numero="2">Etiquetas HTML</capitulo>
<capitulo numero="3">Estilos CSS</capitulo>
<capitulo numero="4">Árbol DOM</capitulo>
<capitulo numero="5">JavaScript</capitulo>
</libro>
</libros>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:l="http://www.esei.uvigo.es/dai/libros">
<xsl:output method="html" indent="yes" encoding="utf-8"/>
<xsl:template match="/">
<xsl:text disable-output-escaping="yes">&lt;!DOCTYPE HTML&gt;</xsl:text>
<html>
<head>
<title>Libros</title>
</head>
<body>
<h1>Lista de Libros</h1>
<xsl:apply-templates select="l:libros/l:libro"/>
</body>
</html>
</xsl:template>
<xsl:template match="l:libro">
<div>
<h2><xsl:value-of select="@titulo"/></h2>
<ol>
<xsl:for-each select="l:capitulo">
<xsl:sort select="@numero"/>
<li><xsl:value-of select="."/></li>
</xsl:for-each>
</ol>
</div>
</xsl:template>
</xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>es.uvigo.esei.dai</groupId>
<artifactId>xml</artifactId>
<version>1.0.0</version>
<name>Ejemplos de DAI - APIs XML</name>
<inceptionYear>2014</inceptionYear>
<url>https://sing-group.org/dt/gitlab/dai-2324/xml</url>
<developers>
<developer>
<name>Miguel Reboiro-Jato</name>
<organization>Escola Superior de Enxeñaría Informática -
Universidade de Vigo</organization>
<organizationUrl>https://esei.uvigo.es/</organizationUrl>
<email>mrjato@uvigo.gal</email>
</developer>
</developers>
<licenses>
<license>
<name>GNU GENERAL PUBLIC LICENSE, Version 3</name>
<url>http://www.gnu.org/licenses/gpl.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Dependencies versions -->
<mysql-connector-j.version>8.1.0</mysql-connector-j.version>
<!-- Plugin versions -->
<license-maven-plugin.version>2.2.0</license-maven-plugin.version>
<maven-compiler-plugin.version>3.11.0</maven-compiler-plugin.version>
<!-- license-maven-plugin configuration -->
<license.licenseName>gpl_v3</license.licenseName>
<license.copyrightOwners>Miguel Reboiro Jato</license.copyrightOwners>
<license.organizationName>Universidade de Vigo</license.organizationName>
<license.addJavaLicenseAfterPackage>false</license.addJavaLicenseAfterPackage>
</properties>
<contributors>
<contributor>
<name>Miguel Reboiro Jato</name>
<email>mrjato@uvigo.gal</email>
<organization>Escola Superior de Enxeñaría Informática -
Universidade de Vigo</organization>
<organizationUrl>https://esei.uvigo.es/</organizationUrl>
<roles>
<role>author</role>
<role>professor</role>
</roles>
</contributor>
</contributors>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>license-maven-plugin</artifactId>
<version>${license-maven-plugin.version}</version>
<executions>
<execution>
<id>first</id>
<goals>
<goal>update-file-header</goal>
</goals>
<phase>process-sources</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
/**
* Temario DAI
* Copyright (C) 2014 Miguel Reboiro-Jato
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.uvigo.esei.dai.xml;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class SimpleErrorHandler implements ErrorHandler {
@Override
public void warning(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void error(SAXParseException exception) throws SAXException {
throw exception;
}
}
\ No newline at end of file
/**
* Temario DAI
* Copyright (C) 2014 Miguel Reboiro-Jato
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.uvigo.esei.dai.xml.dom;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import es.uvigo.esei.dai.xml.SimpleErrorHandler;
public class DOMParsing {
public static Document loadDocument(String documentPath)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del parser del documento
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// factory.setNamespaceAware(true);
final DocumentBuilder builder = factory.newDocumentBuilder();
// Parsing del documento
return builder.parse(new File(documentPath));
}
public static Document loadAndValidateWithInternalDTD(String documentPath)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del parser del documento activando validación
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
// Al construir el parser hay que añadir un manejador de errores
final DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new SimpleErrorHandler());
// Parsing y validación del documento
return builder.parse(new File(documentPath));
}
public static Document loadAndValidateWithInternalXSD(String documentPath)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del parser del documento activando validación
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Al construir el parser hay que añadir un manejador de errores
final DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new SimpleErrorHandler());
// Parsing y validación del documento
return builder.parse(new File(documentPath));
}
public static Document loadAndValidateWithExternalXSD(String documentPath, String schemaPath)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del schema
final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = schemaFactory.newSchema(new File(schemaPath));
// Construcción del parser del documento. Se establece el esquema y se activa
// la validación y comprobación de namespaces
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setSchema(schema);
// Se añade el manejador de errores
final DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new SimpleErrorHandler());
return builder.parse(new File(documentPath));
}
public static String toXML(Document document) throws TransformerException {
// Creación y configuración del transformador. En este caso, se activa
// la indentación del XML
final TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute("indent-number", 3);
final Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// El resultado se almacenará en una cadena de texto
final StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
return writer.toString();
}
}
/**
* Temario DAI
* Copyright (C) 2014 Miguel Reboiro-Jato
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.uvigo.esei.dai.xml.sax;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import es.uvigo.esei.dai.xml.SimpleErrorHandler;
public class SAXParsing {
public static void parseFile(String xmlPath, ContentHandler handler)
throws SAXException, IOException, ParserConfigurationException {
// Construcción del parser SAX
final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setNamespaceAware(true);
// Se añade el handler al parser SAX
final SAXParser parser = parserFactory.newSAXParser();
final XMLReader reader = parser.getXMLReader();
reader.setContentHandler(handler);
// Parsing
try (FileReader fileReader = new FileReader(new File(xmlPath))) {
reader.parse(new InputSource(fileReader));
}
}
public static void parseAndValidatedWithInternalDTD(String xmlPath, ContentHandler handler)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del parser SAX activando la validación
final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setValidating(true);
// Al construir el parser hay que añadir un manejador de errores
final SAXParser parser = parserFactory.newSAXParser();
final XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.setErrorHandler(new SimpleErrorHandler());
// Parsing
try (FileReader fileReader = new FileReader(new File(xmlPath))) {
xmlReader.parse(new InputSource(fileReader));
}
}
public static void parseAndValidateWithInternalXSD(String xmlPath, ContentHandler handler)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del parser del documento. Se activa
// la validación y comprobación de namespaces
final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setValidating(true);
parserFactory.setNamespaceAware(true);
// Se añade el manejador de errores y se activa la validación por schema
final SAXParser parser = parserFactory.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI);
final XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.setErrorHandler(new SimpleErrorHandler());
// Parsing
try (FileReader fileReader = new FileReader(new File(xmlPath))) {
xmlReader.parse(new InputSource(fileReader));
}
}
public static void parseAndValidateWithExternalXSD(String xmlPath, String schemaPath, ContentHandler handler)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del schema
final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = schemaFactory.newSchema(new File(schemaPath));
// Construcción del parser del documento. Se establece el esquema y se activa
// la validación y comprobación de namespaces
final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setValidating(false);
parserFactory.setNamespaceAware(true);
parserFactory.setSchema(schema);
// Se añade el manejador de errores
final SAXParser parser = parserFactory.newSAXParser();
final XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.setErrorHandler(new SimpleErrorHandler());
// Parsing
try (FileReader fileReader = new FileReader(new File(xmlPath))) {
xmlReader.parse(new InputSource(fileReader));
}
}
}
/**
* Temario DAI
* Copyright (C) 2014 Miguel Reboiro-Jato
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.uvigo.esei.dai.xml.tests;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import es.uvigo.esei.dai.xml.dom.DOMParsing;
import es.uvigo.esei.dai.xml.sax.SAXParsing;
public class Tests {
public static void main(String[] args) {
// final File dtdFile = new File("libros.dtd");
final File xsdFile = new File("libros.xsd");
final File xmlFile = new File("libros.xml");
final File xmlXsdFile = new File("libros.xsd.xml");
final File xmlDtdFile = new File("libros.dtd.xml");
final File xmlBadFile = new File("libros.bad.xml");
final File xmlBadXsdFile = new File("libros.xsd.bad.xml");
final File xmlBadDtdFile = new File("libros.dtd.bad.xml");
final File xmlTrainFile = new File("trenes.xml");
System.out.println("======== DOM ========");
try {
DOMParsing.loadAndValidateWithInternalDTD(xmlDtdFile.getAbsolutePath());
System.out.println("Good: OK loadAndValidateWithInternalDTD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Good: Exception loadAndValidateWithInternalDTD");
}
try {
DOMParsing.loadAndValidateWithInternalXSD(xmlXsdFile.getAbsolutePath());
System.out.println("Good: OK loadAndValidateWithInternalXSD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Good: Exception loadAndValidateWithInternalXSD");
}
try {
DOMParsing.loadAndValidateWithExternalXSD(xmlFile.getAbsolutePath(), xsdFile.getAbsolutePath());
System.out.println("Good: OK loadAndValidateWithExternalXSD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Good: Exception loadAndValidateWithExternalXSD");
}
try {
DOMParsing.loadAndValidateWithInternalDTD(xmlBadDtdFile.getAbsolutePath());
System.out.println("Bad: OK loadAndValidateWithInternalDTD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Bad: Exception loadAndValidateWithInternalDTD");
}
try {
DOMParsing.loadAndValidateWithInternalXSD(xmlBadXsdFile.getAbsolutePath());
System.out.println("Bad: OK loadAndValidateWithInternalXSD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Bad: Exception loadAndValidateWithInternalXSD");
}
try {
DOMParsing.loadAndValidateWithExternalXSD(xmlBadFile.getAbsolutePath(), xsdFile.getAbsolutePath());
System.out.println("Bad: OK loadAndValidateWithExternalXSD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Bad: Exception loadAndValidateWithExternalXSD");
}
try {
final Document trains = DOMParsing.loadAndValidateWithInternalXSD(xmlTrainFile.getAbsolutePath());
System.out.println("Trains: List of trains [DOM]");
final NodeList trainNodes = trains.getElementsByTagName("tren");
for (int i = 0; i < trainNodes.getLength(); i++) {
if (trainNodes.item(i) instanceof Element) {
final Element trainElement = (Element) trainNodes.item(i);
final Node salidaNode = trainElement.getElementsByTagName("salida").item(0);
final Node llegadaNode = trainElement.getElementsByTagName("llegada").item(0);
System.out.print(trainElement.getAttribute("ruta"));
System.out.print(" - ");
System.out.print(salidaNode.getTextContent());
System.out.print(" | ");
System.out.println(llegadaNode.getTextContent());
}
}
} catch (ParserConfigurationException | SAXException | IOException e1) {
e1.printStackTrace();
System.out.println("Trains: Exception");
}
System.out.println("\n======== SAX ========");
try {
SAXParsing.parseAndValidatedWithInternalDTD(xmlDtdFile.getAbsolutePath(), new DefaultHandler());
System.out.println("Good: OK parseAndValidatedWithInternalDTD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Good: Exception parseAndValidatedWithInternalDTD");
}
try {
SAXParsing.parseAndValidateWithInternalXSD(xmlXsdFile.getAbsolutePath(), new DefaultHandler());
System.out.println("Good: OK parseAndValidateWithInternalXSD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Good: Exception parseAndValidateWithInternalXSD");
}
try {
SAXParsing
.parseAndValidateWithExternalXSD(xmlFile.getAbsolutePath(), xsdFile.getAbsolutePath(), new DefaultHandler());
System.out.println("Good: OK parseAndValidateWithExternalXSD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Good: Exception parseAndValidateWithExternalXSD");
}
try {
SAXParsing.parseAndValidatedWithInternalDTD(xmlBadDtdFile.getAbsolutePath(), new DefaultHandler());
System.out.println("Bad: OK parseAndValidatedWithInternalDTD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Bad: Exception parseAndValidatedWithInternalDTD");
}
try {
SAXParsing.parseAndValidateWithInternalXSD(xmlBadXsdFile.getAbsolutePath(), new DefaultHandler());
System.out.println("Bad: OK parseAndValidateWithInternalXSD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Bad: Exception parseAndValidateWithInternalXSD");
}
try {
SAXParsing
.parseAndValidateWithExternalXSD(xmlBadFile.getAbsolutePath(), xsdFile.getAbsolutePath(), new DefaultHandler());
System.out.println("Bad: OK parseAndValidateWithExternalXSD");
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Bad: Exception parseAndValidateWithExternalXSD");
}
try {
final TrenesContentHandler contentHandler = new TrenesContentHandler();
SAXParsing.parseAndValidateWithInternalXSD(xmlTrainFile.getAbsolutePath(), contentHandler);
System.out.println("Trains: List of trains [SAX]");
for (final Tren tren : contentHandler.getTrenes()) {
System.out.println(tren);
}
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.println("Trains: Exception");
}
}
}
package es.uvigo.esei.dai.xml.tests;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Tren {
public final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private String ruta;
private Date salida;
private Date llegada;
public Tren() {
}
public Tren(String ruta, Date salida, Date llegada) {
this.ruta = ruta;
this.salida = salida;
this.llegada = llegada;
}
public String getRuta() {
return ruta;
}
public void setRuta(String ruta) {
this.ruta = ruta;
}
public Date getSalida() {
return salida;
}
public void setSalida(Date salida) {
this.salida = salida;
}
public Date getLlegada() {
return llegada;
}
public void setLlegada(Date llegada) {
this.llegada = llegada;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (llegada == null ? 0 : llegada.hashCode());
result = prime * result + (ruta == null ? 0 : ruta.hashCode());
result = prime * result + (salida == null ? 0 : salida.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
return false;
}
final Tren other = (Tren) obj;
if (llegada == null) {
if (other.llegada != null) {
return false;
}
} else if (!llegada.equals(other.llegada)) {
return false;
}
if (ruta == null) {
if (other.ruta != null) {
return false;
}
} else if (!ruta.equals(other.ruta)) {
return false;
}
if (salida == null) {
if (other.salida != null) {
return false;
}
} else if (!salida.equals(other.salida)) {
return false;
}
return true;
}
@Override
public String toString() {
return String.format("%s - %s | %s", this.getRuta(), DATE_FORMAT.format(this.getSalida()), DATE_FORMAT.format(this.getLlegada()));
}
}
package es.uvigo.esei.dai.xml.tests;
import java.text.ParseException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class TrenesContentHandler extends DefaultHandler {
private List<Tren> trenes;
private Tren tren;
private Date lastDate;
public List<Tren> getTrenes() {
return trenes;
}
@Override
public void startDocument() throws SAXException {
this.trenes = new LinkedList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("tren".equals(localName)) {
this.tren = new Tren();
this.tren.setRuta(attributes.getValue("ruta"));
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
final String textContent = new String(ch, start, length);
if (!textContent.trim().isEmpty()) {
try {
this.lastDate = Tren.DATE_FORMAT.parse(textContent);
} catch (final ParseException pe) {
throw new RuntimeException("Invalid date: " + textContent, pe);
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("tren".equals(localName)) {
this.trenes.add(this.tren);
this.tren = null;
} else if ("salida".equals(localName)) {
this.tren.setSalida(this.lastDate);
this.lastDate = null;
} else if ("llegada".equals(localName)) {
this.tren.setLlegada(this.lastDate);
this.lastDate = null;
}
}
}
/**
* Temario
* Copyright (C) 2014 Miguel Reboiro-Jato
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.uvigo.esei.dai.xml.xpath;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.NamespaceContext;
public class NamespaceContextMap implements NamespaceContext {
private final Map<String, String> namespaceToPrefix;
private final Map<String, String> prefixToNamespace;
public NamespaceContextMap() {
this.namespaceToPrefix = new HashMap<>();
this.prefixToNamespace = new HashMap<>();
}
public void putNamespaceURI(String prefix, String namespaceURI) {
this.namespaceToPrefix.put(namespaceURI, prefix);
this.prefixToNamespace.put(prefix, namespaceURI);
}
@Override
public String getNamespaceURI(String prefix) {
return this.prefixToNamespace.get(prefix);
}
@Override
public String getPrefix(String namespaceURI) {
return this.namespaceToPrefix.get(namespaceURI);
}
@Override
public Iterator<String> getPrefixes(String namespaceURI) {
return this.namespaceToPrefix.keySet().iterator();
}
}
\ No newline at end of file
package es.uvigo.esei.dai.xml.xpath;
import java.io.File;
import java.io.StringWriter;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class XSLUtils {
public static Object xpathQueryDOM(Object object, String expression, QName qname) throws XPathExpressionException {
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
return xpath.evaluate(expression, object, qname);
/*
* También sería válido XPathExpression xpExp = xpath.compile(expression); return xpExp.evaluate(object, qname);
*/
}
public static Object xpathQuerySAX(InputSource xmlSource, String expression, QName qname)
throws XPathExpressionException {
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
return xpath.evaluate(expression, xmlSource, qname);
/*
* También sería válido XPathExpression xpExp = xpath.compile(expression); return xpExp.evaluate(xmlSource, qname);
*/
}
public static Object xpathQueryDOM(Object object, String expression, QName returnType, NamespaceContext nsContext)
throws XPathExpressionException {
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
if (nsContext != null) {
xpath.setNamespaceContext(nsContext);
}
return xpath.evaluate(expression, object, returnType);
}
public static Object xpathQuerySAX(
InputSource xmlSource, String expression, QName returnType, NamespaceContext nsContext
) throws XPathExpressionException {
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
if (nsContext != null) {
xpath.setNamespaceContext(nsContext);
}
return xpath.evaluate(expression, xmlSource, returnType);
}
public static void transformWithXSLT(Source xmlSource, Source xsltSource, Result result) throws TransformerException {
final TransformerFactory tFactory = TransformerFactory.newInstance();
final Transformer transformer = tFactory.newTransformer(xsltSource);
transformer.transform(xmlSource, result);
}
public static String transformWithXSLT(File xml, File xslt) throws TransformerException {
final TransformerFactory tFactory = TransformerFactory.newInstance();
final Transformer transformer = tFactory.newTransformer(new StreamSource(xslt));
final StringWriter writer = new StringWriter();
transformer.transform(new StreamSource(xml), new StreamResult(writer));
return writer.toString();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<trenes
xmlns="http://es.uvigo.esei.dai/trenes"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://es.uvigo.esei.dai/trenes trenes.xsd ">
<tren ruta="Ourense-A Coruña">
<salida>2030-10-30T12:00:00</salida>
<llegada>2030-10-30T13:10:00</llegada>
</tren>
<tren ruta="Ourense-Lugo">
<salida>2030-10-30T13:00:00</salida>
<llegada>2030-10-30T14:30:00</llegada>
</tren>
<tren ruta="Ourense-Santiago">
<salida>2030-10-30T14:00:00</salida>
<llegada>2030-10-30T16:00:00</llegada>
</tren>
<tren ruta="Ourense-Vigo">
<salida>2030-10-30T14:30:00</salida>
<llegada>2030-10-30T15:00:00</llegada>
</tren>
</trenes>
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://es.uvigo.esei.dai/trenes"
xmlns:tns="http://es.uvigo.esei.dai/trenes"
elementFormDefault="qualified">
<element name="trenes">
<complexType>
<sequence>
<element name="tren" type="tns:tren" maxOccurs="unbounded" />
</sequence>
</complexType>
</element>
<complexType name="tren">
<sequence>
<element name="salida" type="dateTime" />
<element name="llegada" type="dateTime" />
</sequence>
<attribute name="ruta" type="string" use="required" />
</complexType>
</schema>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment