使用 XMLStarlet,我想向列表中添加另一个属性,
<document>
<properties>
<property>...</property>
<property>...</property> <!-- add this! -->
</properties>
</document>
这很容易,只是“properties”标签是可选的,并且原始文档中可能会丢失,在这种情况下,需要有条件地创建“properties”标签。
最佳答案
ed
子命令没有任何条件,因此没有好的方法,但我认为您可以插入一个新的 properties
元素,然后删除它(如果有)成为“额外”(即不是第一个):
xmlstarlet ed \
-s /document -t elem -n properties -v '' \
-d '/document/properties[position() != 1]' \
-s /document/properties -t elem -n property -v 'new property value' \
doc.xml
否则,您可以先使用 sel
检查并使用 shell 条件来决定是否需要插入。
关于xmlstarlet:如何有条件地添加缺失的元素(upsert),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21489790/