我试图制作一个脚本(理想的是bash或python,所以我学习并且不要愚蠢地使用它)来解析一个看起来像这样的XML文件:
%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\
我试图创建一个可以返回不同属性的脚本。例如:
<?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>
等等。我已经阅读了很多关于XML解析的内容,但是还没有找到任何关于XML文件的内容。任何帮助将不胜感激。
答案 0 :(得分: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
答案 1 :(得分:0)
查看xmlstarlet工具。
http://xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html
使用xmlstarlet,您可以从命令行执行XPath查询。