【发布时间】:2013-09-19 14:16:32
【问题描述】:
我在this discussion 中看到了几个很棒的命令行 XML 操作工具,我正在探索通过脚本而不是编译程序从 XML 文件中提取数据的新方法。我目前正在试用xmlstarlet,但我不限于使用此工具。
我有一个包含数万个元素的 XML 数据文件。我想根据搜索词列表提取这些元素的子集,然后通过管道或其他方式将这些元素路由到一些下游脚本和转换中。搜索词是简单的字符串——不需要正则表达式。如果我在常规文本文件上使用 grep 执行此操作,我可能会执行以下简单操作:
grep -Ff StringsToSearchFor.txt MassiveFile.txt | [chain of additional commands]
我一直在查看 xmlstarlet 之类的工具的文档以了解我可以实现此目的的方法,而我能想到的最接近的方法是使用临时文件的这种丑陋尝试。 (注意,我使用的是 Windows):
REM Create tempOutput.xml, with an open root node
REM %1 is the file containing the list of strings
REM %2 is the target XML file
for /F %%A in (%1) do (
REM Search for a single matching node, and append the output to tempOutput.xml
xml sel -I -t -c "path/to/search[targetElement='%%A']" %2 >> tempOutput.xml
)
REM Close root node to tempOutput.xml
REM After this stage, pass tempOutput.xml as the input to downstream XML transforms and tools
不用说,这真的很丑。
我想一种可能性是修改 for 循环以一次性将大量 -c XPath 查询列表传递给 xmlstarlet,但这似乎也不必要地混乱,我认为我仍然会坚持使用tempOutput.xml 文件。
有没有更优雅的方法来做到这一点?还是临时文件真的是我最好的方法?
【问题讨论】:
标签: xml xpath xmlstarlet