我正在嘗試從 xml 檔案中提取值并將其保存為資料框。對于每個行元素,我想從chk元素中添加日期。
<?xml version="1.0" encoding="ISO-8859-1"?>
<sales>
<chk no="xxx" date="xxxx" time="xxx" total="xxxx" debtor="xxxx" name="xxx" cardnumber="xxxxxxx" mobil="" >
<line productId="xxxx" product="xxxx" productGroupId="xxx" productGroup="xxx" amount="x" price="xxx" />
<line productId="xxx" product="xxx" productGroupId="xxx" productGroup="xxx" amount="xx" price="xxxx" />
</chk>
<chk no="xxx" date="xxxx" time="xx" total="xxxx" debtor="xxxx" name="xxxx" cardnumber="xxxx" mobil="xxxxx" >
<line productId="xxxx" product="xxxxx" productGroupId="xxxx" productGroup="xxx" amount="xxxx" price="xxxx" />
<line productId="xxxxx" product="xxxxx" productGroupId="xxxx" productGroup="xxxx" amount="xxx" price="xxxxx" />
</chk>
</sales>
root = ET.fromstring(response.content)
sales = []
for date in root.iter('chk'):
sales.append(date.attrib)
lines = []
for line in root.iter('line'):
lines.append(line.attrib)
我能夠分別提取 chk 和 line 元素。如何將日期附加到行串列?
uj5u.com熱心網友回復:
import xml.etree.ElementTree as ET
xml = '''<?xml version="1.0" encoding="ISO-8859-1"?>
<sales>
<chk no="xxx" date="xxxx" time="xxx" total="xxxx" debtor="xxxx" name="xxx" cardnumber="xxxxxxx" mobil="" >
<line productId="xxxx" product="xxxx" productGroupId="xxx" productGroup="xxx" amount="x" price="xxx" />
<line productId="xxx" product="xxx" productGroupId="xxx" productGroup="xxx" amount="xx" price="xxxx" />
</chk>
<chk no="xxx" date="zzzz" time="xx" total="xxxx" debtor="xxxx" name="xxxx" cardnumber="xxxx" mobil="xxxxx" >
<line productId="xxxx" product="xxxxx" productGroupId="xxxx" productGroup="xxx" amount="xxxx" price="xxxx" />
<line productId="xxxxx" product="xxxxx" productGroupId="xxxx" productGroup="xxxx" amount="xxx" price="xxxxx" />
</chk>
</sales>'''
root = ET.fromstring(xml)
for chk in root.findall('.//chk'):
for line in chk.findall('line'):
line.attrib['date'] = chk.attrib['date']
ET.dump(root)
uj5u.com熱心網友回復:
迭代 chk 迭代中的行,并使用 date i/o root 作為迭代物件。類似的東西
root = ET.fromstring(resp)
for date in root.iter('chk'):
for line in date.iter('line'):
print(date.attrib,line.attrib)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481329.html
上一篇:SVG到SVG(?)的轉換
