Skip to content

XMLBuilder outputs empty line at the start of output, which breaks XML processors/validators #446

@ceefour

Description

@ceefour
  • Are you running the latest version?
  • Have you included sample input, output, error, and expected output?
  • Have you checked if you are using correct configuration?
  • Did you try online tool?

Description

XMLBuilder outputs empty line at the start of output, which breaks some XML processors.

According to: https://www.stat.auckland.ac.nz/~paul/ItDT/HTML/node46.html#:~:text=The%20first%20line%20of%20an,encoding%20used%20in%20the%20file.

The first line of an XML document should be a declaration that this is an XML document, including the version of XML being used.

Specifically first line, not second line. Even if first line is empty string.

"fast-xml-parser": "^4.0.6"

Input

<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
</testsuites>

Code

import { XMLParser, XMLBuilder, XMLValidator } from "fast-xml-parser";
import fs from "fs";

const parser = new XMLParser({
  ignoreAttributes: false,
  preserveOrder: true,
  cdataPropName: "__cdata",
});
console.info("Parsing junit.xml ...");
const origXml = fs.readFileSync("junit.xml");
const jObj = parser.parse(origXml);
console.debug("Original XML:", origXml.toString("utf8"));
console.info("Parsed.");

// ...

const builder = new XMLBuilder({
  ignoreAttributes: false,
  preserveOrder: true,
  cdataPropName: "__cdata",
  format: true,
});
// console.log(builder.build(jObj));
console.debug(builder.build(jObj));
console.info("Saving to junit.xml ...");
fs.writeFileSync("junit.xml", builder.build(jObj), { encoding: "utf8" });
console.info("Saved.");

Output (buggy)


<?xml   version="1.0" encoding="UTF-8"?>
<testsuites>
</testsuites>
  • note the first empty line
  • not an issue, but not pretty, is that <?xml version="1.0" has too much space

expected output

<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
</testsuites>

workaround

use String.trimStart()

Would you like to work on this issue?

  • Yes
  • No

Bookmark this repository for further updates.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions