我有以下 xml,我想將它決議成一個表。我一直在環顧四周,并沒有找到一個好的答案。困難的部分是:
- 不同子樹中的頭和資料
- 所有內部標簽具有相同的名稱(th 或 td)
| 疫苗 | 日期 | 地位 | 劑量 | 路線 | 地點 | 評論 | ID |
|---|---|---|---|---|---|---|---|
| 疫苗A | 2019年3月15日星期一 | 完畢 | 嗯。 | ||||
| 疫苗B | 2019 年 9 月 20 日,星期二 | 完畢 | 嗯。 |
<ns0:text xmlns:ns0="urn:hl7-org:v3">
<ns0:table border="1" width="100%">
<ns0:thead>
<ns0:tr>
<ns0:th>Vaccine</ns0:th>
<ns0:th>Date</ns0:th>
<ns0:th>Status</ns0:th>
<ns0:th>Dose</ns0:th>
<ns0:th>Route</ns0:th>
<ns0:th>Site</ns0:th>
<ns0:th>Comment</ns0:th>
</ns0:tr>
</ns0:thead>
<ns0:tbody>
<ns0:tr>
<ns0:td>
<ns0:content ID="immunizationDescription1">Vaccin A</ns0:content>
</ns0:td>
<ns0:td>Monday, March 15, 2019 at 4:46:00 pm</ns0:td>
<ns0:td>Done</ns0:td>
<ns0:td>
</ns0:td>
<ns0:td />
<ns0:td />
<ns0:td />
</ns0:tr>
<ns0:tr>
<ns0:td>
<ns0:content ID="immunizationDescription2">Vaccine B</ns0:content>
</ns0:td>
<ns0:td>Tuesday, September 20, 2019 at 12:00:00 am</ns0:td>
<ns0:td>Done</ns0:td>
<ns0:td>
</ns0:td>
<ns0:td />
<ns0:td />
<ns0:td />
</ns0:tr>
</ns0:tbody>
</ns0:table>
</ns0:text>
uj5u.com熱心網友回復:
只要你照顧好你的命名空間,你應該可以接受這樣的事情,盡管它有點令人費解:
from lxml import etree
nsmap = {"ns0": "urn:hl7-org:v3"}
rows = []
cols = doc.xpath('//ns0:thead//ns0:tr//ns0:th/text()', namespaces=nsmap)
cols.append("ID")
for p in doc.xpath('//ns0:tbody//ns0:tr', namespaces=nsmap):
vaccine = p.xpath('.//ns0:content/text()', namespaces=nsmap)[0]
id = p.xpath('.//ns0:content/@ID', namespaces=nsmap)[0]
date = p.xpath('substring-before(.//ns0:td[position()=2]/text()," at")', namespaces=nsmap)
status = p.xpath('.//ns0:td[position()>2]', namespaces=nsmap)
row = []
row.extend([vaccine,date])
row.extend([sta.text.strip() if sta.text else "" for sta in status])
#you could combine the previous two lines into one, but that would make it somewhat less readable
row.append(id)
rows.append(row)
輸出(請原諒格式):
Vaccine Date Status Dose Route Site Comment ID
0 Vaccin A Monday, March 15, 2019 Done immunizationDescription1
1 Vaccine B Tuesday, September 20, 2019 Done immunizationDescription2
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/473563.html
上一篇:Spring 原始碼(14)Spring Bean 的創建程序(5)
下一篇:決議Yaml檔案
