.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

おすすめ記事