Java - Generar XML a partir de un archivo de texto (.txt)

 
Vista:
Imágen de perfil de Alberto Ovalle Méndez
Val: 308
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Generar XML a partir de un archivo de texto (.txt)

Publicado por Alberto Ovalle Méndez (303 intervenciones) el 13/03/2015 17:30:42
Hola, amigos.

Tengo el siguiente archivo de texto (.txt)

XX000000000000000111Example
OO001Test

Donde cada valor de cada linea tiene un limite de caracteres, de acuerdo al ID que se valla leyendo primeramente; es decir, si el ID es igual a XX entonces debe leer los caracteres especificados de acuerdo a ese ID, si el ID es OO entonces leera los especificados para ese ID.

*Producto:
Id (2 caracteres): XX
Codigo(18 caracteres): 000000000000000111
Descripcion(10 caracteres): Example

*Usuario:
Id (2 caracteres): OO
Numero(3 caracteres): 001
Nombre(40 caracteres): Test

Tengo mi aplicacion Java Standalone en donde realizo precisamente esas validaciones correspondientes, como los recupera de una base de datos, los voy cortando si es mayor o si es muy corto lo relleno con espacios o ceros segun sea el caso, por lo tanto, el limite de los valores por cada ID sera fijo.

Me gustaria leer ese archivo y convertirlo a un archivo XML, donde la creacion del archivo XML lo hago con Saxon, mediante la siguiente forma.

try {
Processor proc = new Processor(false);
XsltCompiler comp = proc.newXsltCompiler();
XsltExecutable exp = comp.compile(new StreamSource(new File("archivos/xsl/convertir.xsl")));
Serializer out = new Serializer();
out.setOutputProperty(Serializer.Property.METHOD, "xml");
out.setOutputProperty(Serializer.Property.INDENT, "yes");
out.setOutputFile(new File("archivos/xml/canada.xml"));
XsltTransformer trans = exp.load();
trans.setInitialTemplate(new QName("main"));
trans.setDestination(out);
trans.transform();
} catch (SaxonApiException sae) {
sae.printStackTrace();
}

Si se corre el siguiente codigo me crea el archivo correspondiente, de acuerdo al archivo .xsl que yo eh definido, para este caso hice algo sencillo como se muestra a continuación.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template name="main" match="/">
<producto>
<codigo>8</codigo>
</producto>
</xsl:template>
</xsl:stylesheet>

Ahora, serian tan amables de ayudarme como hago que lea mi archivo de texto para posteriormente ir obteniendo la salida correspondiente.

<producto>
<identificador>XX</identificador>
<codigo>000000000000000111</codigo>
<descripcion>Example</descripcion>
</producto>
<usuario>
<identificador>OO</identificador>
<codigo>001</codigo>
<descripcion>Test</descripcion>
</usuario>

De antemano, muchas gracias por su ayuda.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 349
Bronce
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Generar XML a partir de un archivo de texto (.txt)

Publicado por Andrés (340 intervenciones) el 13/03/2015 20:06:37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Scanner;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
 
class ProductoUsuario {
 
    private String inRoute;
    private String outRoute;
 
    private static final String PRODUCT_IDENTIFIER = "XX";
    private static final String USER_IDENTIFIER = "OO";
 
    public String getInRoute() {
        return inRoute;
    }
 
    public void setInRoute(String inRoute) {
        this.inRoute = inRoute;
    }
 
    public String getOutRoute() {
        return outRoute;
    }
 
    public void setOutRoute(String outRoute) {
        this.outRoute = outRoute;
    }
 
    private void processProduct(String line, XMLStreamWriter writer) throws XMLStreamException {
 
        String id = PRODUCT_IDENTIFIER;
        String code = line.substring(3,20);
        String descripcion = line.substring(20);
 
        writer.writeStartElement("producto");
        writer.writeStartElement("identificador");
        writer.writeCharacters(id);
        writer.writeEndElement();
        writer.writeStartElement("codigo");
        writer.writeCharacters(code);
        writer.writeEndElement();
        writer.writeStartElement("descripcion");
        writer.writeCharacters(descripcion);
        writer.writeEndElement();
        writer.writeEndElement();
 
    }
 
    private void processUser(String line, XMLStreamWriter writer) throws XMLStreamException {
 
        String id = USER_IDENTIFIER;
        String code = line.substring(2,5);
        String descripcion = line.substring(5);
 
        writer.writeStartElement("usuario");
        writer.writeStartElement("identificador");
        writer.writeCharacters(id);
        writer.writeEndElement();
        writer.writeStartElement("codigo");
        writer.writeCharacters(code);
        writer.writeEndElement();
        writer.writeStartElement("descripcion");
        writer.writeCharacters(descripcion);
        writer.writeEndElement();
        writer.writeEndElement();
 
    }
 
    public void processFile() throws Exception {
 
        if (null == this.inRoute || null == this.outRoute) {
            throw new Exception("Are you crazy?");
        }
 
        FileInputStream inputStream = null;
        Scanner sc = null;
        XMLOutputFactory factory = null;
        XMLStreamWriter writer = null;
 
        try {
 
            factory = XMLOutputFactory.newInstance();
            writer = factory.createXMLStreamWriter(new FileWriter(this.outRoute));
 
            inputStream = new FileInputStream(this.inRoute);
            sc = new Scanner(inputStream, "UTF-8");
 
            writer.writeStartDocument();
 
            while (sc.hasNextLine()) {
 
                String line = sc.nextLine();
 
                if(line.startsWith(PRODUCT_IDENTIFIER)) {
                    this.processProduct(line, writer);
                }else  if(line.startsWith(USER_IDENTIFIER)) {
                    this.processUser(line, writer);
                }
 
            }
 
            writer.writeEndDocument();
 
            writer.flush();
            writer.close();
 
            // note that Scanner suppresses exceptions
            if (null != sc.ioException()) {
                throw sc.ioException();
            }
 
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != sc) {
                sc.close();
            }
        }
 
 
    }
 
}
 
/**
 *
 * @author Andrés Mella
 */
public class Main {
 
    public static void main(String[] args) throws Exception {
 
        ProductoUsuario pu = new ProductoUsuario();
        pu.setInRoute("C:\\file.txt");
        pu.setOutRoute("C:\\salida.xml");
        pu.processFile();
    }
 
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Alberto Ovalle Méndez
Val: 308
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Generar XML a partir de un archivo de texto (.txt)

Publicado por Alberto Ovalle Méndez (303 intervenciones) el 13/03/2015 21:55:54
Muchas gracias, Andres.

Sin embargo, la actividad tiene que ser realizada mediante el uso de plantillas XLST eh ahí la razón del porque tengo un archivo .xsl y uso Saxon para la creación del archivo.

Desgraciadamente me rechazaron la propuesta en donde genero el archivo XML mediante código.

Muchas gracias por tu ayuda; completo, entendible y funcional (Aunque le hice unos cambios xD), pero necesito implementar el XLST, ¿Alguna idea de como?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 349
Bronce
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Generar XML a partir de un archivo de texto (.txt)

Publicado por Andrés (340 intervenciones) el 13/03/2015 23:31:47
Revisa:

http://stackoverflow.com/questions/15974377/parse-text-file-with-xslt

If you can use XSLT 2.0 you could use unparsed-text()...

Text File (Do not use the text file as direct input to the XSLT.)
!ITEM_NAME
Item value
!ANOTHER_ITEM
Its value
!TEST_BANG
Here's a value with !bangs!!!

XSLT 2.0 (Apply this XSLT to itself (use the stylesheet as the XML input). You'll also have to change the path to your text file. You might have to change the encoding too.)
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="text-encoding" as="xs:string" select="'iso-8859-1'"/>
<xsl:param name="text-uri" as="xs:string" select="'file:///C:/Users/dhaley/Desktop/test.txt'"/>

<xsl:template name="text2xml">
<xsl:variable name="text" select="unparsed-text($text-uri, $text-encoding)"/>
<xsl:analyze-string select="$text" regex="!(.*)\n(.*)">
<xsl:matching-substring>
<xsl:element name="{normalize-space(regex-group(1))}">
<xsl:value-of select="normalize-space(regex-group(2))"/>
</xsl:element>
</xsl:matching-substring>
</xsl:analyze-string>
</xsl:template>

<xsl:template match="/">
<document>
<xsl:choose>
<xsl:when test="unparsed-text-available($text-uri, $text-encoding)">
<xsl:call-template name="text2xml"/>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="error">
<xsl:text>Error reading "</xsl:text>
<xsl:value-of select="$text-uri"/>
<xsl:text>" (encoding "</xsl:text>
<xsl:value-of select="$text-encoding"/>
<xsl:text>").</xsl:text>
</xsl:variable>
<xsl:message><xsl:value-of select="$error"/></xsl:message>
<xsl:value-of select="$error"/>
</xsl:otherwise>
</xsl:choose>
</document>
</xsl:template>
</xsl:stylesheet>

XML Output
<document>
<ITEM_NAME>Item value</ITEM_NAME>
<ANOTHER_ITEM>Its value</ANOTHER_ITEM>
<TEST_BANG>Here's a value with !bangs!!!</TEST_BANG>
</document>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar