Bash 将子节点插入 XML 文件 [英] Bash insert subnode to XML file

查看:29
本文介绍了Bash 将子节点插入 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码><配置><财产><姓名></姓名><值></值></属性><财产><姓名></姓名><值></值></属性></配置>

我想向文件中添加另外几个 块.由于所有 property 标签都包含在 configuration 标签内,所以文件看起来像这样:

<预><代码><配置><财产><姓名></姓名><值></值></属性><财产><姓名></姓名><值></值></属性><财产><姓名></姓名><值></值></属性></配置>

我看到了这篇文章并遵循接受的答案,但是我的文件中没有附加任何内容,并且我尝试附加的 xml 块作为单行字符串回显".我的 bash 文件如下所示:

file=/path/to/file/oozie-site.xmlcontent="<property>
<name></name>
<value></value>
</property>
<property>
<name></name>
<;值></值>
</属性>"回声$内容C=$(echo $content | sed 's///\//g')sed "//s/.*/${C}
&/" $file

解决方案

使用 xmlstarlet:

xmlstarlet 编辑 --omit-decl -s '//配置' -t elem -n 属性";-s '//配置/属性[last()]' -t elem -n "名称";-s '//配置/属性[last()]' -t elem -n 值";文件.xml

输出:

<预><代码><配置><财产><姓名/><值/></属性><财产><姓名/><值/></属性><财产><姓名/><值/></属性></配置>


<块引用>

--omit-decl:省略 XML 声明

-s:添加一个子节点(参见 xmlstarlet 编辑 详情)

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

-n:设置元素名称

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>

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>

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>
<name></name>
<value></value>
</property>
<property>
<name></name>
<value></value>
</property>"
echo $content
C=$(echo $content | sed 's///\//g')
sed "/</configuration>/ s/.*/${C}
&/" $file

解决方案

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

Output:

<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

这篇关于Bash 将子节点插入 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆