xml - 如何使用 Bash 解析 XML 文件中的某些标记并将它们存储在数组中?

标签 xml bash parsing

我正在尝试解析 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/

相关文章:

android - 如何更改 TextInputLayout 的提示大小

xml - 使用 XSL 合并后如何处理来自多个 XML 文件的所有数据

ruby - 解析文本文件并生成 CSV

c - 如何连接数字字符串然后将其分配给 'long' 类型变量?

java - 将 Eclipse Kepler 仅仅变成一个 XML 编辑器

javascript - 缺少 XML 节点

bash - 当我的 Windows Bash shell 与 Windows 文件系统交互时,它以什么用户身份运行?

windows - Cygwin 中检测运行的 Shell 脚本

linux - bash 中的简单正则表达式解析

c# - 如何使用预定义标记列表实现解析器/解释器?