2011-10-21 29 views
5

Estoy extrayendo datos de XML utilizando XSLT 2.0. Los datos tienen líneas largas y quiero ajustarlos al tamaño de la ventana rompiendo líneas automáticamente.Cómo ajustar el texto para ajustar ventana en XSLT

¿Es posible en XSLT?

+1

¿Cuál es su formato de destino (es decir, xsl: método de salida)? Si eso es HTML o XHTML, los navegadores se asegurarán de que el contenido no se desborde, por lo que no creo que deba hacer nada. Y, por supuesto, el propio XSLT no sabe nada sobre el tamaño de ventanas o ventanas, transforma XML en texto o (X) HTML u otro XML. –

+0

@MartinHonnen Mi salida XML es texto y no XHTML. ¿Es posible si lo entrego en formato de texto? – smandape

Respuesta

6

Puede usar la función estándar XSLT 2.0 unparsed-text() para leer un archivo de texto directamente en su código XSLT 2.0.

Entonces sólo tiene que utilizar:

replace(concat(normalize-space($text),' '), 
       '(.{0,60}) ', 
       '$1
') 

Explicación:

Esta primera normaliza el espacio en blanco, la supresión de la anterior y posterior secuencias de espacios en blanco-sólo caracteres y la sustitución de cualquiera de tales secuencias interior con un solo espacio.

A continuación, el resultado de la normalización se utiliza como primer argumento para la función estándar XPath 2.0 replace().

El patrón de fósforo es cualquier (secuencia más larga posible de un máximo de 61 caracteres que termina con un espacio.

argumento

La sustitución especifica que cualquiera de tales secuencias encontrado debe ser sustituida por la cadena antes de que el espacio que termina, concatenado con una . carácter NL

Aquí es una solución completa, la lectura y dar formato a este texto del archivo C:\temp\delete\text.txt:

Dec. 13 — As always for a presidential inaugural, security and surveillance were 
extremely tight in Washington, DC, last January. But as George W. Bush prepared to 
take the oath of office, security planners installed an extra layer of protection: a 
prototype software system to detect a biological attack. The U.S. Department of 
Defense, together with regional health and emergency-planning agencies, distributed 
a special patient-query sheet to military clinics, civilian hospitals and even aid 
stations along the parade route and at the inaugural balls. Software quickly 
analyzed complaints of seven key symptoms — from rashes to sore throats — for 
patterns that might indicate the early stages of a bio-attack. There was a brief 
scare: the system noticed a surge in flulike symptoms at military clinics. 
Thankfully, tests confirmed it was just that — the flu. 

el código XSLT:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
<xsl:output method="text"/> 

<xsl:variable name="vText" select= 
"unparsed-text('file:///c:/temp/delete/text.txt')"/> 

<xsl:template match="/"> 
    <xsl:sequence select= 
    "replace(concat(normalize-space($vText),' '), 
      '(.{0,60}) ', 
      '$1&#xA;') 
    "/> 
</xsl:template> 
</xsl:stylesheet> 

El resultado es un conjunto de líneas, cada una de las cuales no exceda de una longitud fija de 60:

Dec. 13 — As always for a presidential inaugural, security 
and surveillance were extremely tight in Washington, DC, 
last January. But as George W. Bush prepared to take the 
oath of office, security planners installed an extra layer 
of protection: a prototype software system to detect a 
biological attack. The U.S. Department of Defense, together 
with regional health and emergency-planning agencies, 
distributed a special patient-query sheet to military 
clinics, civilian hospitals and even aid stations along the 
parade route and at the inaugural balls. Software quickly 
analyzed complaints of seven key symptoms — from rashes to 
sore throats — for patterns that might indicate the early 
stages of a bio-attack. There was a brief scare: the system 
noticed a surge in flulike symptoms at military clinics. 
Thankfully, tests confirmed it was just that — the flu. 

actualización:

En caso de que el texto proviene de un archivo XML, esto se puede hacer con un cambio mínimo a la solución anterior:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
<xsl:output method="text"/> 

<xsl:template match="/"> 
    <xsl:sequence select= 
    "replace(concat(normalize-space(text),' '), 
      '(.{0,60}) ', 
      '$1&#xA;') 
    "/> 
</xsl:template> 
</xsl:stylesheet> 

Aquí supongo que todo el texto está en el hijo único nodo de texto del elemento superior (llamado text) del documento XML:

<text> 
Dec. 13 — As always for a presidential inaugural, security and surveillance were 
extremely tight in Washington, DC, last January. But as George W. Bush prepared to 
take the oath of office, security planners installed an extra layer of protection: a 
prototype software system to detect a biological attack. The U.S. Department of 
Defense, together with regional health and emergency-planning agencies, distributed 
a special patient-query sheet to military clinics, civilian hospitals and even aid 
stations along the parade route and at the inaugural balls. Software quickly 
analyzed complaints of seven key symptoms — from rashes to sore throats — for 
patterns that might indicate the early stages of a bio-attack. There was a brief 
scare: the system noticed a surge in flulike symptoms at military clinics. 
Thankfully, tests confirmed it was just that — the flu. 
</text> 

Cuando se aplica esta transformación al documento XML anterior, la Se produce el mismo resultado que con la primera solución.

+1

+1 para una respuesta útil. Tenga en cuenta que OP estaba extrayendo datos de un archivo XML. – LarsH

+0

@LarsH: Oh, gracias, de alguna manera tuve la impresión opuesta: que quería tratar con un archivo de texto sin formato. Agregaré la variante de archivo XML a la solución. –

+0

Wallah! Esto realmente ayuda. Gracias chicos. – smandape

2

Me imagino que tokenize() o <xsl:analyze-string> podrían usarse para hacer esto de manera eficiente, utilizando una expresión regular que permite hasta (digamos) 70 caracteres, y termina con un carácter de ruptura (por ejemplo, el espacio).

Para obtener un código explícito, consulte las respuestas de XPath y XSLT al xquery word wrap.

+2

+1 para una buena respuesta de resumen. –

Cuestiones relacionadas