我之前问过一个问题,它被关闭为重复的:How to parse XML to CSV with a shell script? . 链接的副本中的答案建议使用名为 XMLStarlet 的工具,但我不确定如何在 OS X 上使用此工具。
此外,还有一个标题为“两个标签之间的文本”的问答链接,其中显示了使用xslt
? man xlst
不起作用,但我更深入地研究它,它似乎是某种类型的 Perl 脚本?我在 StackOverflow 上发现了这个,这使我得出了这个结论。
有人可以为我提供一些有关如何在 OS X 上简单地将 XML 文件转换为 CSV 的指导吗?
应用程序 XMLStarlet 似乎可以通过 OSX 使用brew
,因此您应该可以像这样安装它:
$ brew install xmlstarlet
Run Code Online (Sandbox Code Playgroud)
安装后,您可以通过命令行通过命令使用它xmlstarlet
。
$ xmlstarlet
XMLStarlet Toolkit: Command line utilities for XML
Usage: xmlstarlet [<options>] <command> [<cmd-options>]
where <command> is one of:
ed (or edit) - Edit/Update XML document(s)
sel (or select) - Select data or query XML document(s) (XPATH, etc)
tr (or transform) - Transform XML document(s) using XSLT
val (or validate) - Validate XML document(s) (well-formed/DTD/XSD/RelaxNG)
fo (or format) - Format XML document(s)
el (or elements) - Display element structure of XML document
c14n (or canonic) - XML canonicalization
ls (or list) - List directory as XML
esc (or escape) - Escape special XML characters
unesc (or unescape) - Unescape special XML characters
pyx (or xmln) - Convert XML into PYX format (based on ESIS - ISO 8879)
p2x (or depyx) - Convert PYX into XML
<options> are:
-q or --quiet - no error output
--doc-namespace - extract namespace bindings from input doc (default)
--no-doc-namespace - don't extract namespace bindings from input doc
--version - show version
--help - show help
Wherever file name mentioned in command help it is assumed
that URL can be used instead as well.
Type: xmlstarlet <command> --help <ENTER> for command help
XMLStarlet is a command line toolkit to query/edit/check/transform
XML documents (for more information see http://xmlstar.sourceforge.net/)
Run Code Online (Sandbox Code Playgroud)
假设您有这个示例文件,sample.xml
.
$ cat sample.xml
<root>
<record id="1">
<keyA>val_1A</keyA>
<keyB>val_1B</keyB>
</record>
<record id="2">
<keyA>val_2A</keyA>
<keyB>val_2B</keyB>
</record>
<record id="3">
<keyA>val_3A</keyA>
<keyB>val_3B</keyB>
</record>
</root>
Run Code Online (Sandbox Code Playgroud)
要将此文件解析为 CSV,对于每条记录 (1, 2, 3),每条记录对应的值 (keyA, keyB),在一行中您可以使用如下concat
命令:
$ xmlstarlet \
sel -T -t -m /root/record \
-v "concat(@id,',',keyA,',',keyB)" \
-n sample.xml
Run Code Online (Sandbox Code Playgroud)
这将导致以下输出:
1,val_1A,val_1B
2,val_2A,val_2B
3,val_3A,val_3B
Run Code Online (Sandbox Code Playgroud)
上面命令中的workhouse行就是concat()
函数。这是从 XML 记录中获取元素,/root/record
.