如果您已經安裝xmlstarlet,你可以嘗試:命令
[email protected]$ xmlstarlet sel -t -m "//testable" -v trigger -o "|" -v message -o "|" -m sales-info -v san-a -o "|" -v san-b -o "|" -v san-c -n test.xml
Trigger1|2012-06-14T00:03.54|no|no|no
Trigger2|2012-06-15T00:03.54|yes|yes|no
擊穿:
xmlstarlet sel -t
-m "//testable" # match <testable>
-v trigger -o "|" # print out value of <trigger> followed by |
-v message -o "|" # print out value of <message> followed by |
-m sales-info # match <sales-info>
-v san-a -o "|" # print out value of <san-a> followed by |
-v san-b -o "|" # print out value of <san-b> followed by |
-v san-c # print out value of <san-c>
-n # print new line
test.xml # INPUT XML FILE
來定位內<testable>
不同的標籤,你可以嘗試返回文本以下所有葉節點:
[email protected]$ xmlstarlet sel -t -m "//testable" -m "descendant::*[not(*)]" -v 'text()' -i 'not(position()=last())' -o '|' -b -b -n test.xml
Trigger1|2012-06-14T00:03.54|no|no|no
Trigger2|2012-06-15T00:03.54|yes|yes|no
c ommand:
xmlstarlet sel -t
-m "//testable" # match <testable>
-m "descendant::*[not(*)]" # match all leaf nodes
-v 'text()' # print text
-i 'not(position()=last())' -o '|' # print | if not last item
-b -b # break out of nested matches
-n # print new line
test.xml # INPUT XML FILE
如果您沒有訪問xmlstarlet
,那麼就查找您在您的處置有什麼其他的工具。其他選項包括xsltproc(請參閱mzjn's answer)和xpath。
如果這些工具不可用,我會建議使用更高級別的語言(Python,Perl),它允許您訪問正確的XML庫。
雖然可以使用手動regex
解析它,這樣的解決方案將是不理想†特別是不一致的輸入。例如,下面的(假設你有gawk
和sed
)把你的輸入,並應吐出預期輸出:
[email protected]$ gawk 'match($0, />(.*)</, a){printf("%s|",a[1])} /<\/testable>/{print ""}' test.xml | sed 's/.$//'
Trigger1|2012-06-14T00:03.54|no|no|no
Trigger2|2012-06-15T00:03.54|yes|yes|no
然而,這遭到慘敗,如果輸入格式的變化,因此不是一個解決方案,我一般會推薦。
請修正''? –
kev
2012-07-26 08:36:37