gpt4 book ai didi

linux - 在 Bash 中添加 XML 属性

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:14 25 4
gpt4 key购买 nike

我有以下形式的 XML 数据:

<string name="app_name">my App</string>
<string name="yes">Yes</string>
<string name="no">No</string>
<string name="done">Done</string>

我正在尝试编写一个 Bash 脚本来将 XML 转换为如下内容:

<string comment="for more see http://www.web.com/test/app_name" name="app_name">my App</string>
<string comment="for more see http://www.web.com/test/yes" name="yes">Yes</string>

我进行了一些搜索,这是目前为止我找到的内容。

下面的代码正在替换每个元素:

 sed -i 's/<string/<string comment=\"for more see http:\/\/www\.web\.com\/test\/\"    /g' string.xml

此表达式获取 name 属性:

Sname=$(sed '/name/s/\(.*name=\)\(.*\)/\2/' string.xml|awk -F\" '{print $2}')

但我不知道如何合并它们。

最佳答案

使用 sedawk 进行 XML 解析是不安全的。这些工具非常灵活,但它们没有内置的 XML 解析功能。在 sedawk 中实现 XML 解析器非常繁琐且不切实际。我建议使用 XML 解析器,例如 xmlstarlet (实际上它不仅仅是一个解析器)。

示例

xmlstarlet ed -a '//string[@name]' -t attr -n comment src.xml | \
xmlstarlet ed -u '//string/@comment' \
-x 'concat("see http://www.web.com/test/app_name/", ../@name)' > out.xml

第一个xmlstarlet 命令解析src.xml 文件,将一个空的comment 属性附加到所有string 标签具有 name 属性(使用 '//string[@name]' XPath 表达式)。命令的输出通过 pipeline 传递给第二个命令(|)。

第二个命令从管道中读取 XML,并使用 concat() 更新 comment 属性函数,特别是将静态字符串 "see http://www.web.com/test/app_name/"name 属性的值(../@name 代表“父节点的name属性”)。

第二个命令的输出是redirectedout.xml 文件。

示例输入

<root x="10">
<string name="app_name">my App</string>
<string name="yes">Yes</string>
<string name="no">No</string>
<string name="done">Done</string>
</root>

示例输出

<?xml version="1.0"?>
<root x="10">
<string name="app_name" comment="see http://www.web.com/test/app_name/app_name">my App</string>
<string name="yes" comment="see http://www.web.com/test/app_name/yes">Yes</string>
<string name="no" comment="see http://www.web.com/test/app_name/no">No</string>
<string name="done" comment="see http://www.web.com/test/app_name/done">Done</string>
</root>

关于linux - 在 Bash 中添加 XML 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40306572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com