xml - Bash 将子节点插入到 XML 文件

标签 xml bash shell sed xmlstarlet

我正在尝试使用 bash 编辑配置文件。我的文件如下所示:

<configuration>
  <property>
    <name></name>
    <value></value>
  </property>
  <property>
    <name></name>
    <value></value>
  </property>
</configuration>

我想再添加一对 <property> block 到文件。由于所有property标签包含在 configuration 中标记文件看起来像这样:

<configuration>
  <property>
    <name></name>
    <value></value>
  </property>
  <property>
    <name></name>
    <value></value>
  </property>
  <property>
    <name></name>
    <value></value>
  </property>
</configuration>

我遇到了 this post and followed the accepted answer ,但是我的文件没有附加任何内容,我尝试附加的 xml block 被“回显”为单行字符串。 我的 bash 文件如下所示:

file=/path/to/file/oozie-site.xml
content="<property>\n<name></name>\n<value></value>\n</property>\n<property>\n<name></name>\n<value></value>\n</property>"
echo $content
C=$(echo $content | sed 's/\//\\\//g')
sed "/<\/configuration>/ s/.*/${C}\n&/" $file

最佳答案

使用 xmlstarlet:

xmlstarlet edit --omit-decl \
  -s '//configuration' -t elem -n "property" \
  -s '//configuration/property[last()]' -t elem -n "name" \
  -s '//configuration/property[last()]' -t elem -n "value" \
  file.xml

输出:

<configuration>
  <property>
    <name/>
    <value/>
  </property>
  <property>
    <name/>
    <value/>
  </property>
  <property>
    <name/>
    <value/>
  </property>
</configuration>

--omit-decl: omit XML declaration

-s: add a subnode (see xmlstarlet edit for details)

-t elem: set node type, here: element

-n: set name of element

关于xml - Bash 将子节点插入到 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42962889/

相关文章:

java - "This Activity already has an action bar supplied by the window decor..."错误

android - 链接以从 xml 字符串资源中的 android 应用程序发送电子邮件

xml - XPATH,用于将节点与通配符匹配并具有一个属性,但没有另一个属性

bash - 如何在现有的Docker容器中永久设置环境变量?

linux - shell 如何找到/etc/passwd 中的最后一个条目

linux - 从 bash shell 启动一个新的 bash shell

java - ANT build.xml 删除目录任务不起作用

bash - 将参数正确传递给 docker 入口点

bash - 从文本文件中删除 Unicode 字符 - sed ,其他 Bash/shell 方法

string - 如何在unix中剪切特定字符后的字符串