我有这个 XML 文件:
<?xml version="1.0" encoding="UTF-8" ?>
<engineConfiguration xmlns="http://bla.com/engine/management/engineConfiguration">
<engineParameter>
<name>PORT_ID</name>
<value>47827</value>
</engineParameter>
<engineParameter>
<name>POS_PRINTER_PORT_ID</name>
<value>27001</value>
</engineParameter>
<engineParameter>
<name>PDS_WS_LOCATION</name>
<value>http://localhost:8080/pds-jbrain-ws/pdsservice?wsdl</value>
</engineParameter>
</engineConfiguration>
我正在尝试更新该POS_PRINTER_PORT_ID
值,但我很难做到正确。
我已经尝试过以下命令:
xmlstarlet ed -u '/engineConfiguration/engineParameter/POS_PRINTER_PORT_ID' -v 9999 engineConfiguration.xml
xmlstarlet ed -N s=http://bla.com/engine/management/engineConfiguration -u '/s:engineConfiguration/s:engineParameter[name = "POS_PRINTER_PORT_ID"]/value' -v 999 engineConfiguration.xml
我也在尝试,xmllint
但读到这xmlstarlet
是可行的方法。
答案1
您上次的尝试几乎是正确的,但您忘记将命名空间添加到name
和value
节点:
xmlstarlet ed \
-N s=http://bla.com/engine/management/engineConfiguration \
-u '/s:engineConfiguration/s:engineParameter[s:name = "POS_PRINTER_PORT_ID"]/s:value' \
-v 9999 file.xml
或者使用从命令行导入的参数而不是表达式中的硬编码值:
xmlstarlet ed \
-N s='http://bla.com/engine/management/engineConfiguration' \
--var n "'POS_PRINTER_PORT_ID'" --var v "'9999'" \
-u '/s:engineConfiguration/s:engineParameter[s:name = $n]/s:value' \
-x '$v' file.xml
使用xq
:
xq -x '( .engineConfiguration.engineParameter[] |
select(.name == "POS_PRINTER_PORT_ID").value ) |= 9999' file.xml
带参数:
xq --arg n 'POS_PRINTER_PORT_ID' --arg v 9999 \
-x '( .engineConfiguration.engineParameter[] |
select(.name == $n).value ) |= $v' file.xml