使用 xmlstarlet 添加 xml 元素中尚不存在的属性

Add attribute that does not yet exist in xml element with xmlstarlet

我有一个 xml 文件以

开头
<?xml version='1.0' encoding='utf-8'?>
<widget 
  id="io.ionic.starter" 
  version="0.0.1" 
  xmlns="http://www.w3.org/ns/widgets" 
  xmlns:cdv="http://cordova.apache.org/ns/1.0"
>

我需要添加一个 ios-CFBundleVersion="de.test" 属性,因此它应该如下所示:

<?xml version='1.0' encoding='utf-8'?>
<widget 
  id="io.ionic.starter" 
  version="0.0.1" 
  xmlns="http://www.w3.org/ns/widgets" 
  xmlns:cdv="http://cordova.apache.org/ns/1.0"
  ios-CFBundleVersion="de.test"
>

我试过 xmlstarlet:

xmlstarlet edit \
  -O \
  --inplace \
  --insert "widget" \
  --type attr \
  -n ios-CFBundleVersion \
  -v de.test \
  config.xml 

但我的文件 config.xml 没有任何反应。此处正确的 xmlstarlet 命令是什么?

您忘记了 widget 元素有一个命名空间,因此您的 XPath 不匹配。因此,使用 -N 全局选项 定义一个,您的命令开始工作:

xmlstarlet edit --inplace -O -N x=http://www.w3.org/ns/widgets  \
                --insert "x:widget" --type attr \
                -n "ios-CFBundleVersion" -v "de.test" config.xml