NaturalIntelligence / fast-xml-parser

Validate XML, Parse XML and Build XML rapidly without C/C++ based libraries and no callback.
https://naturalintelligence.github.io/fast-xml-parser/
MIT License
2.58k stars 309 forks source link

Feature Request: Allow tags with empty children to be build as an unpaired tag #677

Closed iyxan23 closed 2 months ago

iyxan23 commented 2 months ago

Hey there!

I've been using your library fast-xml-parser v4 and it's been great, but I've run into a small issue that I think could be improved.

Currently, if a tag doesn't have any children, it would be nice if it could be automatically made self-closing. For example, consider this XML:

<a>
  <b>hello</b>
  <c></c>
</a>

As it went through the parser and builder, it would be awesome if the output could be:

<a>
  <b>hello</b>
  <c />
</a>

Right now, to make a tag self-closing, I have to list it as an unpaired tag with the unpairedTag field, but that means it can't have nested values at all. It would be really helpful if there was an option to make tags self-closing dynamically based on whether they have children or not.

Perhaps creating a new option like dynamicUnpairedTags could help? Here's how it could work:

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

const jsonObj = /* json object that represents `<a><b>hello</b><c></c></a>` */

const options = {
  dynamicUnpairedTags: true // New option to enable dynamic unpaired tags
};

const xmlOutput = new XMLBuilder(options).build(jsonObj);
console.log(xmlOutput);
// Output: <a><b>hello</b><c /></a>

I'm not really sure if this is a standard thing in the XML world – I'm pretty new to all this. Right now, I'm working on a project to make small changes to OOXML documents without completely parsing everything, keeping the xmls as close to the original as possible. The problem is, some office software won't accept unpaired tags if they're written like regular tags.

My current workaround is to keep a big list of unpaired tags, but that's kind of a pain and could break if it runs into unknown unpaired tags.

If you'd like, I could try working a PR for this, though I can't provide an exact time frame or window. But I'd be happy to work on it when I have the time.

Thanks, keep up the great work!

github-actions[bot] commented 2 months ago

We're glad you find this project helpful. We'll try to address this issue ASAP. You can vist https://solothought.com to know recent features. Don't forget to star this repo.

amitguptagwl commented 2 months ago

As I remember there is a property to suppress empty tags into self closing tag. please check docs.

iyxan23 commented 2 months ago

As I remember there is a property to suppress empty tags into self closing tag. please check docs.

https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/docs/v4/3.XMLBuilder.md#suppressemptynode

Genuinely apologize, I did not realize the option was in front of my face this whole time. Thank you!