我正在尝试解析 XML 文件并跟踪某些元素以将它们存储在数组中。
示例 XML 文件 trouble.xml 如下所示:
<trouble>
<problem>
<factor name = abc/>
</problem>
<problem>
<factor name = def/>
</problem>
<trouble>
这些并在 trouble.xml 中重复多次。
我能够使用这个:
echo 'cat //factor/@name' | xmllint --shell $filename | sed -n 's: name=\"\(.*\)\":\1:p'
输出看起来像这样:
abc
def
此代码片段成功打印了因子标签的“名称”。我现在的问题是找到一种方法以某种方式遍历该名称列表并将它们保存到数组中?
最佳答案
使用 mapfile,您不需要循环遍历结果
#!/usr/bin/env bash
# Read the array from the output of processing xml
mapfile -t array < <(
xmllint --shell <<<'cat //factor/@name' a.xml |
sed -n 's: name=\"\(.*\)\":\1:p'
)
# Debug print the array declaration
typeset -p array
测试数据的实际输出:
declare -a array=([0]="abc" [1]="def")
以防您的 bash 太旧而无法提供 mapfile
。这是另一种方法:
#!/usr/bin/env bash
# Read the array from the output of processing xml
IFS=$'\n' read -r -d '' -a array < <(
xmllint --shell <<<'cat //factor/@name' a.xml |
sed -n 's: name=\"\(.*\)\":\1:p'
)
关于xml - 如何使用 Bash 解析 XML 文件中的某些标记并将它们存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63163788/