讀取 .xml 檔案並將資訊寫入 .txt 文件

讀取 .xml 檔案並將資訊寫入 .txt 文件

我想從線上 ChartServer 下載河流徑流 (.xml) 文件,並透過執行 .sh 腳本建立包含該資訊的 .txt 檔案。但我很難以正確的格式取得數據。

我添加了腳本的一部分,希望有人能指出我如何讓它發揮作用的正確方向。

url="http://h-web01.nve.no/ChartServer/ShowData.aspx?req=getchart&ver=1.0&time=-10;0&vfmt=xml&chd=ds=htsr,rt=1,da=18,id=700.2.2.1001.0"

xmllint --xpath '//SeriesData/Serie/Point/Value' ${url} | tr '</Value>' '\n' | grep -v '^$' > value_2.2.txt
xmllint --xpath '//SeriesData/Serie/Point/DateTime' ${url} | tr '</DateTime>' '\n' | grep -v '^$' > datetime.txt

if [ -s datetime.txt ]; then
    while true; do
      read month     || break
      read day       || break
      read year      || break
      read hour      || break
      echo ${year} ${month} ${day} >> date_2.2.txt
done < datetime.txt

# Put the date and runoff file together
while read Q <&3 && read y m d <&4; do
    echo ${y} ${m} ${d} ${Q} >> runoff_2.2.txt
done 3<value_${fra}.${til}.txt 4<date_2.2.txt

我希望 .txt 檔案包含:

yyyy month day value

但是我的程式碼只給了value每個其他“DateTime”:

yyyy hh:mm:ss month day value
yyyy hh:mm:ss month day 
yyyy hh:mm:ss month day value
...

來源資料

<?xml version="1.0" encoding="utf-8"?>
<SeriesData>
  <Serie>
    <Legend>Glomma med kystområder (700.2.2), Vannføring (m³/s)</Legend>
    <Point>
      <DateTime>03/07/2020 12:00:00</DateTime>
      <Value>673.2365</Value>
    </Point>
    <Point>
      <DateTime>03/08/2020 12:00:00</DateTime>
      <Value>695.2465</Value>
    </Point>
    <Point>
      <DateTime>03/09/2020 12:00:00</DateTime>
      <Value>786.8168</Value>
    </Point>
    <Point>
      <DateTime>03/10/2020 12:00:00</DateTime>
      <Value>766.8459</Value>
    </Point>
    <Point>
      <DateTime>03/11/2020 12:00:00</DateTime>
      <Value>758.2921</Value>
    </Point>
    <!-- ...more data... -->
    <Point>
      <DateTime>03/16/2020 12:00:00</DateTime>
      <Value>702.8088</Value>
    </Point>
    <Statistics/>
  </Serie>
</SeriesData>

答案1

如果你不介意使用xmlstarlet代替xmllint你可以使用這個

url="http://h-web01.nve.no/ChartServer/ShowData.aspx?req=getchart&ver=1.0&time=-10;0&vfmt=xml&chd=ds=htsr,rt=1,da=18,id=700.2.2.1001.0"
curl --silent "$url" |
    xmlstarlet sel -t -m '//SeriesData/Serie/Point' -v 'concat(substring(DateTime,7,4)," ",substring(DateTime,1,2)," ",substring(DateTime,4,2)," ",Value)' -n

不幸的是,該<DateTime/>元素不是正確的 XML 日期,因此我們必須手動拆分它,而不是使用 XPath 日期處理函數。

輸出

2020 03 07 673.2365
2020 03 08 695.2465
2020 03 09 786.8168
2020 03 10 766.8459
2020 03 11 758.2921
...
2020 03 16 702.8088

相關內容