Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pretty print XML from the command line?

Related: How can I pretty-print JSON in (unix) shell script?

Is there a (unix) shell script to format XML in human-readable form?

Basically, I want it to transform the following:

<root><foo a="b">lorem</foo><bar value="ipsum" /></root> 

... into something like this:

<root>     <foo a="b">lorem</foo>     <bar value="ipsum" /> </root> 
like image 782
svidgen Avatar asked Apr 18 '13 18:04

svidgen


People also ask

How do I print an XML file?

Browse for the XML file by clicking File->Open or pressing Ctrl+O. Click File->Print or press Ctrl+P to open the Printer window.

How do I beautify XML in Visual Studio?

To access XML formatting options, choose Tools > Options > Text Editor > XML, and then choose Formatting.

How do you make a pretty print in Notepad ++?

Click on Plugins Menu, Select XML Tools -> Pretty Print or Pretty Print - Indent attributes or Pretty Print - Indent only option or you can choose shortcut key CTRL+ALT+Shift+A or CTRL+ALT+Shift+A command.


1 Answers

xmllint

This utility comes with libxml2-utils:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |     xmllint --format - 

Perl's XML::Twig

This command comes with XML::Twig perl module, sometimes xml-twig-tools package:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |     xml_pp 

xmlstarlet

This command comes with xmlstarlet:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |     xmlstarlet format --indent-tab 

tidy

Check the tidy package:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |     tidy -xml -i - 

Python

Python's xml.dom.minidom can format XML (works also on legacy python2):

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |     python -c 'import sys; import xml.dom.minidom; s=sys.stdin.read(); print(xml.dom.minidom.parseString(s).toprettyxml())' 

saxon-lint

You need saxon-lint:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |     saxon-lint --indent --xpath '/' - 

saxon-HE

You need saxon-HE:

 echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |     java -cp /usr/share/java/saxon/saxon9he.jar net.sf.saxon.Query \     -s:- -qs:/ '!indent=yes' 
like image 128
Gilles Quenot Avatar answered Oct 04 '22 10:10

Gilles Quenot