首页 > 解决方案 > 有没有办法使用 xmllint 在 XML 树上追溯?

问题描述

目前正在使用 Bash 解析 XML 文件的项目。例如,如果我有 bookstore.xml:

<bookstore>
    <genre name = "Childrens">
       <book>
           <author>
           <title name = "Cat in the Hat">
       </book>
    </genre/
    <genre name = "Young Adult">
       <book>
           <author>
           <title name = "Twilight">
       </book>
    </genre>
</bookstore>
...

鉴于我已经能够从 xml 文件中提取所有 </title/> 名称。我现在正在尝试使用给定的 </title/> 并以某种方式向后追溯并找到其各自的 </genre/> 并以某种方式使用关联数组将书的 </title/> 映射到 </genre/>。例如:

books[$title] = $genre
books["Cat in the Hat"] = "Childrens"

我相信,第一步是在知道我已经将 </titles/> 保存在单独的数组中的情况下检索该流派名称。我最终的目标是从本质上比较一个仅包含书名的单独 xml 文件,并将其与 bookstore.xml 进行比较。当我运行程序并将其与 bookstore.xml 进行比较时,程序将读取输入文件中的所有时间并返回每个标题的类型。作为另一个参考,这是我如何从给定的 bookstore.xml 文件中提取标题以及我想要完成的工作。

TITLES=$(echo 'cat //title/@name' | xmllint --shell $filename | sed -n 's: name=\"\(.*\)\":\1:p') 

for title in $TITLES; do
      BOOKS[$title]="[this will be its respective genre somehow]"
done

最后,如果我输入一个只有标题的 xml 文件并将其与 bookstore.xml 进行比较,输出应如下所示:

Title: Cat in the Hat Genre: Children's
Title: Twilight Genre: Young Adult

请对此提供帮助,如果需要进一步澄清,请告诉我!先感谢您。

标签: xmlbashxmllint

解决方案


要将标题和类型转换为变量,请使用:

titles=$(xmllint --xpath //genre/book/title/@name  file.xml)

names=$(xmllint --xpath //genre/@name  file.xml)

如果你可以使用 xmlstarlet 来代替,它更简单,你不需要使用变量:

xmlstarlet select -T -t -m //genre -v " concat('Title: ',book/title/@name, ' ','Genre: ',@name)" -n file.xml

推荐阅读