gpt4 book ai didi

python - 在命令行中解析 XML 文件(理想情况下是 bash/python)

转载 作者:太空宇宙 更新时间:2023-11-03 14:00:00 25 4
gpt4 key购买 nike

我正在尝试制作一个脚本(最好是 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 文件的内容。任何帮助将不胜感激。

最佳答案

完整的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

关于python - 在命令行中解析 XML 文件(理想情况下是 bash/python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49322847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com