Shell-Script

需要將數據從xml解析到shell腳本

  • April 5, 2018

需要一個接一個地從xml解析數據到shell腳本

Requriment :- we need to take <FileSetfolder> as one record. XML may contain many <FileSetFolder> from Each <FileSetFolder> record. 
we need to extract <path> and <Filetypes> and archive all the files which are with extension type as <Filetypes> 
need help in approach for this requirement

ex:- for first <FileSetfolder>
   Archive_path = D:\apache-2.4.10\htdocs
   Filetypes =(rep,zip,mnt)

   need to archive files in $Archive_path which have $Filetypes (rep,zip,mnt)

   then it should take next <FileSetfolder>

XML:-

<SourceFolder>
   <FileSetFolder>
     <Path>D:\apache-2.4.10\htdocs</Path>
     <FileType>rep</FileType>
     <FileType>zip</FileType>
     <FileType>mnt</FileType>
   </FileSetFolder>
   <FileSetFolder>
     <Path>D:\Download\ROSXcenterAutoArchive\ArchiveStorage\archive</Path>
     <FileType>mnt</FileType>
     <FileType>952230</FileType>
   </FileSetFolder>
 </SourceFolder>

使用XMLStarlet(有時安裝為xmlstarlet而不是xml):

paths=( $( xml sel -t -v '//FileSetFolder/Path' file.xml ) )

for path in "${paths[@]}"; do
   filetypes=( $( xml sel -t -v "//FileSetFolder[Path=\"$path\"]/FileType" file.xml ) )

   for filetype in "${filetypes[@]}"; do
           printf 'Path "%s" has a filetype "%s"\n' "$path" "$filetype"
   done
done

輸出:

Path "D:\apache-2.4.10\htdocs" has a filetype "rep"
Path "D:\apache-2.4.10\htdocs" has a filetype "zip"
Path "D:\apache-2.4.10\htdocs" has a filetype "mnt"
Path "D:\Download\ROSXcenterAutoArchive\ArchiveStorage\archive" has a filetype "mnt"
Path "D:\Download\ROSXcenterAutoArchive\ArchiveStorage\archive" has a filetype "952230"

引用自:https://unix.stackexchange.com/questions/435664