【问题标题】:Bash insert subnode to XML fileBash 将子节点插入 XML 文件
【发布时间】:2017-08-15 05:32:22
【问题描述】:

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

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

我想在文件中添加另外几个 &lt;property&gt; 块。由于所有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 块是作为单行字符串“回显”的。 我的 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

【问题讨论】:

  • 使用 XML/HTML 解析器(xmllint、xmlstarlet ...)。

标签: xml bash shell sed xmlstarlet


【解决方案1】:

使用 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:设置节点类型,这里:元素

-n: 设置元素名称

【讨论】:

  • 尝试一下 - 当我运行这个命令时,它会在终端中打印出我的配置文件以及添加的子节点。但是,当我在 vim 中检查文件时,似乎没有附加任何内容
  • Nvm 。我添加了 file.xml > newfile.xml 并查看了更改。多谢。最后一个问题,如何添加多个块?只要有更多这些 `-s '//configuration/property[last()]' -t elem -n "value" ` ?
  • 如果定义了命名空间,则需要指定...stackoverflow.com/questions/17615428/…
【解决方案2】:

将最后一行改为sed -i.BAK "/&lt;\/configuration&gt;/ s/.*/${C}\n&amp;/" $file

【讨论】:

  • 你的回答对一些解释会更有帮助。
猜你喜欢
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多