使用xmllint寻找多个值

时间:2019-04-24 10:21:16

标签: bash xmllint

我需要从一个XML文件中的几个XML块中检索一个以上的值。如何使用xmllint做到这一点?

我注意到此解决方案(xml_grep get attribute from element)并尝试扩展它。不幸的是,到目前为止没有任何运气。

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "orderNumber": "[&1].orderNumber",
        "items": {
          "*": {
            "itemQuantity": "[&1].items[].itemQuantity",
            "item": {
              "external_id": "[&1].items[].external"
            }
          }
        }
      }
    }
}
]

示例XML文件:

xmllint --xpath 'string(//identity/@name @placeofbirth @photo)' file.xml

想要输出

 <eid>
   <identity>
      <name>Menten</name>
      <firstname>Kasper</firstname>
      <middlenames>Marie J</middlenames>
      <nationality>Belg</nationality>
      <placeofbirth>Sint-Truiden</placeofbirth>
      <photo>base64-string</photo>
    </identity>
    <identity>
      <name>Herbal</name>
      <firstname>Jane</firstname>
      <middlenames>Helena</middlenames>
      <nationality>Frans</nationality>
      <placeofbirth>Paris</placeofbirth>
      <photo>notavailable</photo>
    </identity>
 </eid>

1 个答案:

答案 0 :(得分:1)

一种实现方法是

# Read xml into variable
xmlStr=$(cat test.xml)
# Count identity nodes
nodeCount=$(echo "$xmlStr" | xmllint --xpath "count(//identity)" -)
# Iterate the nodeset by index
for i in $(seq 1 $nodeCount);do
   echo "$xmlStr" | xmllint --xpath "concat((//identity)[$i]/name,', ',(//identity)[$i]/placeofbirth, ', ', (//identity)[$i]/photo)" - ; echo
done

结果:

Menten, Sint-Truiden, base64-string
Herbal, Paris, notavailable