使用 xmlStarlet 更新 xml 属性值

Update xml attribute values using xmlStarlet

        <?xml version="1.0"?>
<Student xmlns="http://www.tibco.com/schemas/TrainingPOCs/SharedRec/Schemas/Schema.xsd">
  <Phno type="kwh" value="70" name=""/>
  <Phno type="wh" value="100" name="80">
    <Type>D</Type>
    <Mobile>7777777777</Mobile>
    <TPhone>6666666666</TPhone>
  </Phno>
  <Phno type="kwh" value="200" name="">
    <Type>E</Type>
    <Mobile>5555555555</Mobile>
    <TPhone>4444444444</TPhone>
  </Phno
</Student>

我的输入文件 只要 type 属性有 kWh 脚本,我就需要用 value 属性值更新 name 属性

xmlstarlet edit -N w="http://www.tibco.com/schemas/TrainingPOCs/SharedRec/Schemas/Schema.xsd" -u "/w:Student/w:Phno[@type='kwh']/@name" -x "/w:Student/w:Phno[@type='kwh']/@value" sample.xml

您快完成了,但是使用相对 XPath 表达式 -x / --expr 选项:

xmlstarlet edit \
    -N w='http://www.tibco.com/schemas/TrainingPOCs/SharedRec/Schemas/Schema.xsd' \
    -u '/w:Student/w:Phno[@type="kwh"]/@name' \
    -x 'string(../@value)' file.xml

或者,使用默认命名空间 shortcut,

xmlstarlet ed -u '/_:Student/_:Phno[@type="kwh"]/@name' -x 'string(../@value)' file.xml

并可能添加 -L / --inplace 选项(请参阅 xmlstarlet.txt) 用于就地编辑。