如何使用xmlstarlet将不同的属性添加到xmlfile的每个节点 [英] How to add diferent attributes to each node of an xmlfile using xmlstarlet

查看:168
本文介绍了如何使用xmlstarlet将不同的属性添加到xmlfile的每个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在bash脚本中使用xmlstarlet编辑xml文件.
但是我发现在尝试为相同节点中的相同属性赋予不同值时遇到问题,让我通过以下示例向您展示:
使用此代码

I was trying to edit an xml file using xmlstarlet in a bash script.
But I found I have a problem when trying to give different values to the same attributes in the same nodes, let me show you with this example:
Using this code

xmlstarlet ed -L -s /foo -t elem -n bar -v "" -i //bar -t attr -n id -v bar1 $file  
xmlstarlet ed -L -s /foo -t elem -n bar -v "" -i //bar -t attr -n id -v bar2 $file

使用此命令,我在$ file中得到以下结果:

using this i get the following result in $file:

<foo>
  <bar id="bar1" id="bar2"/>
  <bar id="bar2"/>
</foo>

但是我想要达到的目标是这样的:

But what I am trying to achieve looks like this:

<foo>
  <bar id="bar1"/>
  <bar id="bar2"/>
</foo>

你能帮我吗?

推荐答案

使用此文件:

<foo>
</foo>

命令:

xmlstarlet edit --omit-decl \
   --subnode "//foo" --type elem -n "bar" \
   --insert "//bar[1]" --type attr -n "id" --value "bar1" \
   --subnode "//foo" --type elem -n "bar" \
   --insert "//bar[2]" --type attr -n "id" --value "bar2" file.xml 

如果您不想计算新元素,请使用last():

If you don't want to count new elements use last():

xmlstarlet edit --omit-decl \
   --subnode "//foo" --type elem -n "bar" \
   --insert "//bar[last()]" --type attr -n "id" --value "bar1" \
   --subnode "//foo" --type elem -n "bar" \
   --insert "//bar[last()]" --type attr -n "id" --value "bar2" file.xml

两种情况下的输出:

<foo>
  <bar id="bar1"/>
  <bar id="bar2"/>
</foo>

这篇关于如何使用xmlstarlet将不同的属性添加到xmlfile的每个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆