Bash将子节点插入XML文件 [英] Bash insert subnode to XML file
问题描述
我正在尝试使用bash编辑配置文件.我的文件如下所示:
Im trying to edit a config file using bash. My file looks like this:
<configuration>
<property>
<name></name>
<value></value>
</property>
<property>
<name></name>
<value></value>
</property>
</configuration>
我想在文件中添加另外两个<property>
块.由于所有property
标记都包含在configuration
标记内,因此文件看起来像这样:
I want to add another couple of <property>
blocks to the file. Since all property
tags are enclosed inside the configuration
tags the file would looks like this:
<configuration>
<property>
<name></name>
<value></value>
</property>
<property>
<name></name>
<value></value>
</property>
<property>
<name></name>
<value></value>
</property>
</configuration>
我遇到了此帖子并遵循接受的答案,但是没有任何内容附加到我的文件中,而我尝试附加的xml块作为单个行字符串被回显". 我的bash文件如下所示:
I came across this post and followed the accepted answer, however nothing is appended to my file and the xml block I try to append is "echo-ed" as a single line string. My bash file looks like this:
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:
With 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
了解详情)
-s
: add a subnode (see xmlstarlet edit
for details)
-t elem
:设置节点类型,此处:元素
-t elem
: set node type, here: element
-n
:设置元素名称
这篇关于Bash将子节点插入XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!