如何使用XmlStarlet将具有属性的元素插入XML文件?

时间:2022-12-01 11:09:22

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:

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

<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追加元素:

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. 什么是XPath表达式,它选择没有name属性的每个 元素?

  3. Can I append the elements and insert the attributes with a single xml ed command?
  4. 我可以附加元素并使用单个xml ed命令插入属性吗?

1 个解决方案

#1


4  

Answers

  1. /xml/block/el[not(@name)]
  2. As stated in an other answer:
  3. 如其他答案所述:

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'

#1


4  

Answers

  1. /xml/block/el[not(@name)]
  2. As stated in an other answer:
  3. 如其他答案所述:

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'