`preserveOrder: true` with `format: true` formats mixed content wrongly and adds whitespace to content that ends with `>`

Abierto Apto para principiantes
#31 0 comentarios 0 reacciones 0 asignados Ver en GitHub

@neumaennl ya está trabajando en esto.

Desde el 10/11/2026.

  • #32 de @neumaennl — abierto

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
84/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
javascript
Área
backend

Línea de trabajo

Empieza por la lógica de formato de arrToStr() descrita en el issue y comprueba cómo procesa cada entrada hija, incluidos los elementos, los comentarios, las instrucciones de procesamiento y los nodos de parada. Añade casos de regresión para los seis ejemplos y compara el XML generado con la salida esperada; el issue estará terminado cuando el contenido mixto se formatee correctamente sin añadir espacios en blanco al contenido que no tenga etiquetas hijas.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Description

With preserveOrder: true and format: true, arrToStr() decides how to format an element's content by looking at the generated string: whether it ends with >, or contains /> or </. That check gets several cases wrong. Some of them only look odd, others add whitespace to the content:

  1. Whitespace-only line. If the first child is a tag and text follows later, the output gets a line that contains only the indentation, because the content already starts with its own line break and indentation.
  2. Closing tag on the text's line. If a comment or processing instruction is followed by text, the content contains neither /> nor </, so the closing tag follows the text directly.
  3. Unindented text. If text is followed by a tag, the content ends with >, so the text is written directly after the opening tag.
  4. Whitespace added to content without child tags. If the content ends with > but has no child tag, a line break and indentation are added before the closing tag. This happens with CDATA-only content, with text ending in > when processEntities is false, and with the raw content of stop nodes.
Code
import XMLBuilder from "fast-xml-builder"; // 1.3.1

const options = { preserveOrder: true, format: true, commentPropName: "#comment", cdataPropName: "#cdata" };
const builder = new XMLBuilder(options);
const text = (value) => [{ "#text": value }];

builder.build([{ p: [{ b: text("two") }, { "#text": "three" }] }]);   // 1
builder.build([{ q: [{ "#comment": text("c") }, { "#text": "three" }] }]); // 2
builder.build([{ r: [{ "#text": "one" }, { b: text("two") }] }]);     // 3
builder.build([{ d: [{ "#cdata": text("a") }] }]);                    // 4
new XMLBuilder({ ...options, processEntities: false }).build([{ x: text("a>") }]); // 4
new XMLBuilder({ ...options, stopNodes: ["root.script"] })
  .build([{ root: [{ script: [{ b: text("x") }] }] }]);               // 4
Output
"\n<p>\n  \n  <b>two</b>\n  three\n</p>"
"\n<q>\n  <!--c-->\n  three</q>"
"\n<r>one\n  <b>two</b>\n</r>"
"\n<d><![CDATA[a]]>\n</d>"
"\n<x>a>\n</x>"
"\n<root>\n  <script><b>x</b>\n  </script>\n</root>"
Expected output
"\n<p>\n  <b>two</b>\n  three\n</p>"
"\n<q>\n  <!--c-->\n  three\n</q>"
"\n<r>\n  one\n  <b>two</b>\n</r>"
"\n<d><![CDATA[a]]></d>"
"\n<x>a></x>"
"\n<root>\n  <script><b>x</b></script>\n</root>"

The leading line break is a separate question (#30).

A fix would decide by the child entries instead of the string: the content is written on lines of its own only if a child is an element, a comment or a processing instruction, and never for a stop node.

Would you like to work on this issue?

  • Yes
  • No
Lenguaje dominante
JavaScript
Estrellas
22
Forks
9
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de NaturalIntelligence/fast-xml-builder

Todos los issues de NaturalIntelligence/fast-xml-builder

Issues similares

Más issues de JavaScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.