如何使用最大子属性更新 XML 属性节点?

How can I update an XML attribute node with the maximum of its sub-attributes?

考虑以下 XML:

<?xml version="1.0"?>
<sportsClass>
    <pupils>
        <pupil name="Adam" highestJump="">
            <jump height="4"/>
            <jump height="1"/>
        </pupil>
        <pupil name="Berta" highestJump="">
            <jump height="4"/>
            <jump height="7"/>
        </pupil>
        <pupil name="Caesar" highestJump="">
            <jump height="1"/>
            <jump height="2"/>
        </pupil>
        <pupil name="Doris" highestJump="">
            <jump height="5"/>
            <jump height="5"/>
        </pupil>
    </pupils>
</sportsClass>

如何使用 xmlstarlet 为 highestJump 属性节点填充相应的最大 height 值?

这个问题由两个子问题组成:

求最大值

xmlstarlet没有max()这个功能,所以我们得想办法:

cat jumps.xml | \
xmlstarlet select -t -v "//pupil/jump[not(@height <= following-sibling::jump/@height) and not(@height < preceding-sibling::jump/@height)]/@height"

注意 <=< – 如果有多个最大值,则只取最后一个。

结果:

4
7
2
5

正在更新属性

练习的恒定值

cat jumps.xml | xmlstarlet edit --update //pupil/@highestJump -v "Hahahaha"

...将 Hahahaha 写入每个 highestJump 属性。

简单的 XPath

注意:用于替换

的 XPath
  • 相对于所选属性(因此 .属性本身
  • 必须用例如包裹起来。 string()要有效果

所以:

cat jumps.xml | xmlstarlet edit --update //pupil/@highestJump -x "string(../@name)"

...给出(缩短):

<pupil name="Adam" highestJump="Adam">
<pupil name="Berta" highestJump="Berta">
<pupil name="Caesar" highestJump="Caesar">
<pupil name="Doris" highestJump="Doris">

结合两者

cat jumps.xml | xmlstarlet edit --update //pupil/@highestJump -x "string(../jump[not(@height <= following-sibling::jump/@height) and not(@height < preceding-sibling::jump/@height)]/@height)"

...给出...

<?xml version="1.0"?>
<sportsClass>
  <pupils>
    <pupil name="Adam" highestJump="4">
      <jump height="4"/>
      <jump height="1"/>
    </pupil>
    <pupil name="Berta" highestJump="7">
      <jump height="4"/>
      <jump height="7"/>
    </pupil>
    <pupil name="Caesar" highestJump="2">
      <jump height="1"/>
      <jump height="2"/>
    </pupil>
    <pupil name="Doris" highestJump="5">
      <jump height="5"/>
      <jump height="5"/>
    </pupil>
  </pupils>
</sportsClass>