是否可以使用xmlstarlet将计算出的属性(即非常数)插入XML文件?

问题描述 投票:1回答:1

我有这样的XML文件:

sources.xml

<?xml version="1.0" encoding="UTF-8"?>
<sources>
  <source>
    <identity id="abc"/>
    <somestuff/>
  </source>
  <source>
    <identity id="def"/>
    <someotherstuff/>
  </source>
</sources>

我想摆脱标签identity,并将其属性转移到父节点中。换句话说,我需要将输入文件更改为:

<?xml version="1.0" encoding="UTF-8"?>
<sources>
  <source id="abc">
    <somestuff/>
  </source>
  <source id="def">
    <someotherstuff/>
  </source>
</sources>

我尝试过:

xmlstarlet edit \
  --insert "//source" --type attr --name "id" --value "identity/@id" \
  --delete "//identity" \
  sources.xml

这不起作用,因为--value将其参数理解为常量字符串。

我的问题是:[[xmlstarlet是否有可能像id操作中那样将属性select的值计算为XPATH表达式?

编辑nr。 1

我找到了一种在该方向上完成工作的方法:

xmlstarlet edit \ --insert "//source" --type attr --name "id" --value "{PLACE HOLDER}" \ --update "//source/@id" --expr "../identity/@id" \ --delete "//identity" \ sources.xml

但是我得到属性id的空值:

<?xml version="1.0" encoding="UTF-8"?> <sources> <source id=""> <somestuff>Hello</somestuff> </source> <source id=""> <someotherstuff/> </source> </sources>

表达式../identity/@id中怎么了?
xml xmlstarlet
1个回答
1
投票
xmlstarlet edit \ --insert "//source" --type attr --name "id" \ --update "//source/@id" --expr "string(../identity/@id)" \ --delete "//identity" \ sources.xml

我们需要使用XPATH函数--expr将作为选项string()的参数给出的文本节点转换为字符串。

© www.soinside.com 2019 - 2024. All rights reserved.