Bash将子节点插入XML文件

时间:2017-03-22 21:22:24

标签: xml bash shell sed xmlstarlet

我尝试使用bash编辑配置文件。我的文件看起来像这样:

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

我想在文件中添加另外几个<property>块。由于所有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块是&#34; echo-ed&#34;作为单行字符串。 我的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

2 个答案:

答案 0 :(得分:5)

使用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:省略XML声明

     

-s:添加子节点(有关详细信息,请参阅xmlstarlet edit

     

-t elem:设置节点类型,这里:element

     

-n:设置元素名称

答案 1 :(得分:0)

sed -i.BAK "/<\/configuration>/ s/.*/${C}\n&/" $file

更改最后一行
相关问题