fast-xml-parser icon indicating copy to clipboard operation
fast-xml-parser copied to clipboard

Incorrect formatting from XMLBuilder

Open mfsasso opened this issue 3 years ago • 1 comments

Checklist

  • [ ] Have you asked your question on Stackoverflow or similar forum?
  • [x] Are you running the latest version?
  • [x] Have you included sample input, output, error, and expected output?
  • [ ] Have you checked if you are using correct configuration?
  • [x] Did you try online tool?

Input

Code

const { XMLParser, XMLBuilder, XMLValidator } = require('fast-xml-parser');

const xml = `<?xml version="1.0" encoding="UTF-8"?>
<person>
    <name>
        <first>M</first>
        <last>S</last>
    </name>
    <location>somewhere</location>
</person>
`;

console.log( xml );

if( XMLValidator.validate(xml) === true ) {

    const parser = new XMLParser({
        ignoreAttributes: false,
        ignoreDeclaration: false,
        alwaysCreateTextNode: true,
    });
    const json = parser.parse(xml);
    console.log( JSON.stringify(json, null, 4) );

    const builder = new XMLBuilder({
        ignoreDeclaration: false,
        ignoreAttributes: false,
        format: true,
        indentBy: '    '
    });
    const newXml = builder.build( json );
    console.log( newXml );

}

Output

Console log of source XML:
<?xml version="1.0" encoding="UTF-8"?>
<person>
    <name>
        <first>M</first>
        <last>S</last>
    </name>
    <location>somewhere</location>
</person>

Console log of JSON (stringified) from parser:
{
    "?xml": {
        "@_version": "1.0",
        "@_encoding": "UTF-8"
    },
    "person": {
        "name": {
            "first": {
                "#text": "M"
            },
            "last": {
                "#text": "S"
            }
        },
        "location": {
            "#text": "somewhere"
        }
    }
}

Console log of xml from builder:
<?xml version="1.0" encoding="UTF-8"?><person>
    <name>
        <first>M</first>
        <last>S</last>
    </name>
    <location>somewhere</location>
</person>

expected data

Result XML should match source XML. Specifically, person tag should be on a separate line.

Would you like to work on this issue?

  • [ ] Yes
  • [x] No

Bookmark this repository for further updates.

mfsasso avatar Jul 07 '22 20:07 mfsasso

I'm glad you find this repository helpful. I'll try to address your issue ASAP. You can watch the repo for new changes or star it.

github-actions[bot] avatar Jul 07 '22 20:07 github-actions[bot]

Please reopen if still exists

amitguptagwl avatar Jan 10 '23 03:01 amitguptagwl