【问题标题】:Parsing a XML file in command line (bash/python ideally)在命令行中解析 XML 文件(理想情况下是 bash/python)
【发布时间】:2018-03-16 14:14:28
【问题描述】:

我正在尝试制作一个脚本(理想情况下是 bash 或 python,所以我学习而不只是愚蠢地使用它)来解析一个如下所示的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<fruits xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://whatever/fruits.xsd" timestamp="1521126010" merchantId="xxxx">
<fruit id="1" name="Orange" color="orange"/>
<fruit id="2" name="Mandarine" color="Orange"/>
<fruit id="3" name="Raisin" color="Green" variety="4"/>
<fruit id="4" name="Raspberrry" color="red" variety="2"/>
<fruit id="5" name="Kiwi" color="brown"/>
<fruit id="6" name="I am a fruit" variety="7">
</fruits>

我正在尝试制作一个可以返回不同属性的脚本。例如:

./script Raisin -c
Orange
./script Kiwi -v
No variety defined
./script "I am a fruit" -i
6

等等。我已经阅读了很多关于 XML 解析的内容,但还没有找到任何关于这种 XML 文件的内容。任何帮助将不胜感激。

【问题讨论】:

  • 您的-i 选项是什么意思?描述你所有的选择
  • 就 python 而言,有一个名为 etree 的模块包含在 lxml 中。这将允许您在 python 运行时轻松解析 XML 数据。
  • @RomanPerekhrest : -i 代表 id,-c 代表颜色,-v 代表品种
  • @Kyle :会检查一下,谢谢!
  • " 还没有找到任何关于那种 XML 文件的东西" => 像 XML 这样的格式的要点是它们是通用的。 IOW 你可以使用任何可用的 Python XML 解析器来完成这项工作。

标签: python xml bash parsing


【解决方案1】:

完成bash + xmlstarlet解决方案:

get_attr.sh脚本:

#!/bin/bash

name=$1
declare -A attr_map
attr_map=(["-c"]=color ["-i"]=id ["-v"]=variety)

if [[ -z "$2" ]]; then
    echo "Additional attribute missing!"
    exit 1
fi

if [[ -z "${attr_map[$2]}" ]]; then
    echo "Unsupported attribute prefix. Allowed are: ${!attr_map[@]}"
    exit 1
fi

attr="${attr_map[$2]}"
result=$(xmlstarlet sel -t -m "//fruit[@name='$name' and @$attr]" -v "./@$attr" input.xml)
if [[ -n "$result" ]]; then
    echo "$result"
else
    echo "No $attr attribute defined"
fi

测试用例:

$ bash get_attr.sh "Orange" -c
orange
$ bash get_attr.sh "Raisin" -v
4
$ bash get_attr.sh "Raisin" -d
Unsupported attribute prefix. Allowed are: -v -c -i
$ bash get_attr.sh "I am a fruit" -i
6
$ bash get_attr.sh "I am a fruit" -c
No color attribute defined

【讨论】:

  • 非常感谢!肯定会为我的下一个脚本检查 xmlstartlet 的东西!
【解决方案2】:

查看 xmlstarlet 工具。

http://xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html

使用 xmlstarlet,您可以从命令行执行 XPath 查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2020-01-02
    • 2015-11-04
    • 1970-01-01
    • 2016-11-01
    • 2017-11-07
    • 2013-06-07
    相关资源
    最近更新 更多