前書き
Python の標準ライブラリ に含まれている(xml.etree.ElementTree, csv, os) を使ってスプリクトを書いた方が簡単で、その後のデータの加工など使い勝手がいいことから、「ahcd-go」をやめて、pythonにしました。
環境
iMac Retina 5k, 27-inch, 2017
macOS Ventura 13.7.4
MacBook Air (15インチ, M2, 2023)
MacOS:Sonoma14.5
実行結果
exportDataディレクトリに、変換後のcsvができる
あとは、通常の方法でdataframeなどで、加工する
python3スクリプト
import os
import csv
import xml.etree.ElementTree as ET
# -----------------------------------------------------
xml_file = "export.xml" # XMLファイルのパス
output_dir = "exportData" # CSV出力フォルダ
# 必要なデータのマッピング
FILE_NAME_MAPPING = {
"HKQuantityTypeIdentifierActiveEnergyBurned",
"HKQuantityTypeIdentifierBasalEnergyBurned",
"HKQuantityTypeIdentifierBodyFatPercentage",
"HKQuantityTypeIdentifierBodyMass",
"HKQuantityTypeIdentifierStepCount",
"HKQuantityTypeIdentifierWalkingSpeed",
"HKQuantityTypeIdentifierWalkingStepLength",
"HKQuantityTypeIdentifierDistanceWalkingRunning"
}
# XML を解析
tree = ET.parse(xml_file)
root = tree.getroot()
# 出力フォルダの作成
os.makedirs(output_dir, exist_ok=True)
# 各データを適切なCSVに保存
for record in root.findall("Record"):
record_type = record.get("type")
if record_type not in FILE_NAME_MAPPING:
continue # 不要なデータはスキップ
file_name = f"{record_type}.csv"
file_path = os.path.join(output_dir, file_name)
# 新規作成時にヘッダーを追加
write_header = not os.path.exists(file_path) or os.stat(file_path).st_size == 0
with open(file_path, mode="a", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
if write_header:
writer.writerow(["作成日", "Value", "StartDate", "EndDate"])
# 取得するデータを書き込む
writer.writerow([
record.get("creationDate", ""),
record.get("value", ""),
record.get("startDate", ""),
record.get("endDate", "")
])
print("XMLからCSVへの変換が完了しました。")
<ご参考>iPhoneからヘルスケアの”xmlデータ”の取得方法
・「ヘルスケア」アプリを開きます。
・右上にある写真またはイニシャルをタップします。
・「すべてのヘルスケアデータを書き出す」をタップします。
・「書き出す」をクリック
・「書き出したデータ」で好きなところにダウンロードする
・例:「ファイルに保存」からPCのFinderにダウンロード
(事前に保存するディレクトリを作っておくか決めておく)
以上です。