Is there any CLI tool for Linux which formats XML files keeping any empty lines and comments? I have tried xmllint, tidy and xmlstarlet, but all seem to focus completely cleaning XML files rather than just indentation and spacing.
-
Can you give an example of what you want to achieve?choroba– choroba2019-01-01 20:46:59 +00:00Commented Jan 1, 2019 at 20:46
-
2Stack Overflow is for programming questions, not questions about using or configuring Linux and its applications. Super User or Unix & Linux would be better places for questions like this.Barmar– Barmar2019-01-01 21:30:14 +00:00Commented Jan 1, 2019 at 21:30
-
1Not sure why this was downvoted. Linters, code formators, and co are definitely programming related.machinekoder– machinekoder2019-01-02 11:10:55 +00:00Commented Jan 2, 2019 at 11:10
-
1This is a request for a CLI tool, and therefore off-topic for Stack Overflow.E_net4– E_net42019-01-06 16:34:36 +00:00Commented Jan 6, 2019 at 16:34
Add a comment
|
1 Answer
Try xmlindent. It has several options like -nbe and -nba and others that configure the handling of spaces before and after.
Given an XML input of
<?xml version="1.0"?>
<Response>
<TroubleResponse>
<Check>
<DStatus>
<GID>123456789</GID>
<FLAG/>
</DStatus>
</Check>
<RAM>
<Details>
<RAMID>5555777788
</RAMID>
</Details>
</RAM>
<RAM>
<Details>
<RAMID>
5555777788</RAMID>
</Details>
</RAM>
</TroubleResponse>
</Response>
The output can be configured with the following options (an excerpt):
-t Use tabs instead of spaces
-nas Suppress newline after start-tag
-nae Suppress newline after end-tag
-nbs Suppress newline before start-tag
-nbe Suppress newline before end-tag
-f Force newline on elements without children
So xmlindent -f and xmlindent -nba would produce the following output:
<?xml version="1.0"?>
<Response>
<TroubleResponse>
<Check>
<DStatus>
<GID>123456789 <!-- Change -->
</GID>
<FLAG/>
</DStatus>
</Check>
<RAM>
<Details>
<RAMID>5555777788
</RAMID>
</Details>
</RAM>
<RAM>
<Details>
<RAMID> <!-- Change -->
5555777788
</RAMID>
</Details>
</RAM>
</TroubleResponse>
</Response>
And xmlindent -nbe would produce the following output:
<?xml version="1.0"?>
<Response>
<TroubleResponse>
<Check>
<DStatus>
<GID>123456789</GID>
<FLAG/>
</DStatus>
</Check>
<RAM>
<Details>
<RAMID>5555777788
</RAMID>
</Details>
</RAM>
<RAM>
<Details>
<RAMID> <!-- Change -->
5555777788</RAMID>
</Details>
</RAM>
</TroubleResponse>
</Response>
xmlindent is not perfect as it does not seem to always realize the expected outcome, but it can be somewhat configured.
2 Comments
machinekoder
Thank you very much.
xmlindent -nbe does what I want.Chris Wolf
I had to build
xmlindent for MacOS, which required hacks to the build - I used cmake - once I get rid of local idiosyncrasies, I'll post a PR.