以下に説明するXMLファイルがあり、unixコマンドを使用してアプリケーション名、コンピュータ、およびステータスタグの値を抽出し、それをカンマ区切り形式で表示したいとします。
XMLファイル:-
<?xml version="1.0" encoding="UTF-8"?>
<applications>
<application name="Adapter/Code1">
<service name="Code1.par">
<deploymentStatus>Success</deploymentStatus>
<serviceInstance name="Code1-One">
<machine>123</machine>
<status>Running</status>
</serviceInstance>
<serviceInstance name="Code1-Two">
<machine>456</machine>
<status>Running</status>
</serviceInstance>
</service>
</application>
<application name="Adapter/Code2">
<service name="Code2.par">
<deploymentStatus>Success</deploymentStatus>
<serviceInstance name="Code2-One">
<machine>123</machine>
<status>Running</status>
</serviceInstance>
<serviceInstance name="Code2-Two">
<machine>456</machine>
<status>Running</status>
</serviceInstance>
</service>
</application>
</applications>
出力:-
Adapter/Code1,123,Running
Adapter/Code1,456,Running
Adapter/Code2,123,Running
Adapter/Code2,456,Running
このアクティビティを実行するためのunixcommand / shellスクリプトを提供できますか?
よろしくお願いします! ! !
ベストアンサー1
Python3.xソリューション(xml.etree.ElementTree標準寸法):
import xml.etree.ElementTree as ET
tree = ET.parse("test.xml")
root = tree.getroot()
for app in root.findall('application'):
for m,s in zip(app.iter('machine'), app.iter('status')):
print("%s,%s,%s" % (app.get('name'), m.text, s.text))
出力:
Adapter/Code1,123,Running
Adapter/Code1,456,Running
Adapter/Code2,123,Running
Adapter/Code2,456,Running
xmlstarlet+アッ(application
各要素の子ノードをグループ化するための)回避策:
xmlstarlet sel -t -v "//application/@name| .//machine/text()| .//status/text()" -n input.xml
| awk '/Adapter/{app=$0; r=app; c=0; next}
{ if(++c==2){ c=0; print r","$0; r=app } else { r=r","$0 }}'
出力:
Adapter/Code1,123,Running
Adapter/Code1,456,Running
Adapter/Code2,123,Running
Adapter/Code2,456,Running
"//application/@name| .//machine/text()| .//status/text()"
- 必要なノードを取得するためのXPath式/Adapter/{app=$0; r=app; c=0; next}
-application
追加の接続のために各名前をキャプチャします。