通过它们之间的值搜索 XML 标签并在 shell 脚本中插入新标签 [英] Searching for XML tag by value between them and inserting a new tag in shell script

查看:38
本文介绍了通过它们之间的值搜索 XML 标签并在 shell 脚本中插入新标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含这些内容的 test.xml 文件

Say I have this test.xml file which has these contents

<d>
  <p>
    <n>hi</n>
    <r>
      <s>1.0</s>
    </r>
  </p>

  <p>
    <n>hello</n>
    <r>
      <s>1.0</s>
    </r>
  </p>
</d>

我想为hello"对象添加一个新的 <s>2.0</s>,如下所示.

I want to add a new <s>2.0</s> for "hello" object as shown below.

<d>
  <p>
    <n>hi</n>
    <r>
      <s>1.0</s>
    </r>
  </p>

  <p>
    <n>hello</n>
    <r>
      <s>1.0</s>
      <s>2.0</s>
    </r>
  </p>
</d>

我必须使用 shell 脚本来做到这一点.有一种方法可以搜索 XML DOM 并使用此处给出的 xmlstarlet 添加标签 http://www.technomancy.org/xml/add-a-subnode-command-line-xmlstarlet/ .但这仅描述了基于属性值向某些节点添加新标签.我没有任何属性.我该怎么做 ?有没有办法使用 grep 做到这一点?

I have to do this using shell script. There is a way of searching through the XML DOM and adding tags using xmlstarlet given here http://www.technomancy.org/xml/add-a-subnode-command-line-xmlstarlet/ . But this only describes adding new tag to certain nodes based on attribute value. I do not have any attributes. How can I do it ? Is there any way of doing it using grep ?

推荐答案

xmlstarlet ed -a '//p[n="hello"]/r/s' -t elem -n s -v 2.0 input.xml

说明:

  • ed ==> 编辑
  • -a ==> 追加
  • -t ==> 类型
  • -n ==> 名字
  • -v ==> 值
  • Explanation:

    • ed ==> edit
    • -a ==> append
    • -t ==> type
    • -n ==> name
    • -v ==> value
    • 这篇关于通过它们之间的值搜索 XML 标签并在 shell 脚本中插入新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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