相关:如何在(unix) shell脚本漂亮打印JSON ?
是否有(unix) shell脚本以人类可读的形式格式化XML ?
基本上,我想要它转换如下:
<root><foo a="b">lorem</foo><bar value="ipsum" /></root>
…变成这样:
<root>
<foo a="b">lorem</foo>
<bar value="ipsum" />
</root>
相关:如何在(unix) shell脚本漂亮打印JSON ?
是否有(unix) shell脚本以人类可读的形式格式化XML ?
基本上,我想要它转换如下:
<root><foo a="b">lorem</foo><bar value="ipsum" /></root>
…变成这样:
<root>
<foo a="b">lorem</foo>
<bar value="ipsum" />
</root>
当前回答
xidel:
xidel -s input.xml -se . --output-node-format=xml --output-node-indent
<root>
<foo a="b">lorem</foo>
<bar value="ipsum"/>
</root>
或者file:write("output.xml",.,{"indent":true()})保存到文件中。
其他回答
xmllint
这个实用程序附带libxml2-utils:
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
xmllint --format -
Perl的XML::树枝
这个命令附带了XML::Twig perl模块,有时是XML - Twig -tools包:
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
xml_pp
xmlstarlet
这个命令附带xmlstarlet:
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
xmlstarlet format --indent-tab
tidy
检查整齐的包装:
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
tidy -xml -i -
Python
Python的XML .dom.minidom可以格式化XML(也适用于遗留的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
你需要撒克逊棉:
echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
saxon-lint --indent --xpath '/' -
saxon-HE
你需要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'
您没有提到文件,所以我假设您想在命令行上提供XML字符串作为标准输入。在这种情况下,请执行以下操作:
$ echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' | xmllint --format -
Xmllint——格式化yourxmlfile.xml
xmllint是一个命令行XML工具,包含在libxml2 (http://xmlsoft.org/)中。
================================================
注意:如果你没有安装libxml2,你可以通过以下方法安装它:
被久远
cd /tmp
wget ftp://xmlsoft.org/libxml2/libxml2-2.8.0.tar.gz
tar xzf libxml2-2.8.0.tar.gz
cd libxml2-2.8.0/
./configure
make
sudo make install
cd
Ubuntu
Sudo apt-get安装libxml2-utils
Cygwin
Apt-cyg安装libxml2
操作系统
要在MacOS和Homebrew上安装此程序,请执行以下操作: 酿造安装libxml2
Git
如果你想要代码,也可以在Git上使用: Git克隆Git://git.gnome.org/libxml2
你也可以使用tidy,它可能需要先安装(例如在Ubuntu上:sudo apt-get install tidy)。
为此,您可以发布如下内容:
tidy -xml -i your-file.xml > output.xml
注意:有许多额外的可读性标志,但是换行行为有点烦人(http://tidy.sourceforge.net/docs/quickref.html)。
xidel:
xidel -s input.xml -se . --output-node-format=xml --output-node-indent
<root>
<foo a="b">lorem</foo>
<bar value="ipsum"/>
</root>
或者file:write("output.xml",.,{"indent":true()})保存到文件中。