如何使用 XmlStarlet 将具有属性的元素插入 XML 文件? [英] How to insert elements with attributes to an XML file using XmlStarlet?

查看:36
本文介绍了如何使用 XmlStarlet 将具有属性的元素插入 XML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

源 XML

<块><el name="a">92346</el><el name="b">lorem</el><块><el name="a">89753</el><el name="b">ipsum</el></xml>

对象

我想使用 Linux shell 脚本在每个 中插入一个 0 元素:

<块><el name="a">92346</el><el name="b">lorem</el><el name="c">0</el><块><el name="a">89753</el><el name="b">ipsum</el><el name="c">0</el></xml>

我可以使用 XmlStarlet 附加元素:

xmlstarlet ed -a '/xml/block/el[@name="b"]' \--type 'elem' -n 'el' -v 0

问题

  1. 选择每个 元素的 XPath 表达式是什么?没有 name 属性?
  2. 我可以附加元素并使用单个属性插入属性吗?xml ed 命令?

解决方案

答案

  1. /xml/block/el[not(@name)]
  2. 其他答案所述:

<块引用>

您不能直接插入带有属性的元素,但因为每个编辑操作都是按顺序执行的,您可以插入一个元素,然后添加一个属性.

命令

xmlstarlet ed -a '/xml/block/el[@name="b"]' \-t 'elem' -n 'el' -v 0 \-i '/xml/block/el[not(@name)]' \-t '属性' -n '名称' -v 'c'

Source XML

<xml>
    <block>
        <el name="a">92346</el>
        <el name="b">lorem</el>
    </block>
    <block>
        <el name="a">89753</el>
        <el name="b">ipsum</el>
    </block>
</xml>

Object

I would like to insert an <el name="c">0</el> element in every <block> with a Linux shell script:

<xml>
    <block>
        <el name="a">92346</el>
        <el name="b">lorem</el>
        <el name="c">0</el>
    </block>
    <block>
        <el name="a">89753</el>
        <el name="b">ipsum</el>
        <el name="c">0</el>
    </block>
</xml>

I can append the elements using XmlStarlet:

xmlstarlet ed -a '/xml/block/el[@name="b"]' \
              --type 'elem' -n 'el' -v 0

Questions

  1. What is the XPath expression that selects every <el> element which doesn't have a name attribute?
  2. Can I append the elements and insert the attributes with a single xml ed command?

解决方案

Answers

  1. /xml/block/el[not(@name)]
  2. As stated in an other answer:

You can't insert an element with an attribute directly but since every edit operation is performed in sequence, you can insert an element and then add an attribute.

The command

xmlstarlet ed -a '/xml/block/el[@name="b"]' \
              -t 'elem' -n 'el' -v 0 \
              -i '/xml/block/el[not(@name)]' \
              -t 'attr' -n 'name' -v 'c'

这篇关于如何使用 XmlStarlet 将具有属性的元素插入 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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