【问题标题】:How do I parse certain tags from an XML file and store them in an array using Bash?如何解析 XML 文件中的某些标签并使用 Bash 将它们存储在数组中?
【发布时间】:2020-07-29 23:10:01
【问题描述】:

我对 bash 脚本非常陌生。我正在尝试解析 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

这段代码 sn-p 成功打印了因子标签的“名称”。我现在的问题是找到一种方法以某种方式遍历该名称列表并将它们保存到数组中?

请帮忙,提前谢谢。

【问题讨论】:

  • myArr=( $(cat ....|xmllint ...| sed ...) ) ?祝你好运。

标签: xml bash parsing


【解决方案1】:

使用 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'
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2012-09-29
    相关资源
    最近更新 更多