簡體   English   中英

使用 Python 從 xml 中的子節點導出信息

[英]Export information from child nodes in xml using Python

我有一個名為 people.xml 的 xml 文件,格式如下:

<?xml version="1.0" encoding="UTF-8"?>
<persons>
  <person id="1" name="John">
    <city id="21" name="New York"/>
  </person>
  <person id="2" name="Mary">
    <city id="22" name="Los Angeles"/>
  </person>
</persons>

我想將人名列表以及城市名稱導出到文件中

import pandas as pd
import xml.etree.ElementTree as ET
tree = ET.parse('./persons.xml')
root = tree.getroot()

df_cols = ["person_name", "city_name"]
rows = []

for node in root: 
    person_name = node.attrib.get("name")

    rows.append({"person_name": person_name})

out_df = pd.DataFrame(rows, columns = df_cols)    
out_df

顯然,這部分代碼僅適用於獲取名稱,因為它是根的一部分,但我不知道如何循環遍歷子節點並獲取此信息。 我是否需要 append 一些東西來遍歷子節點?

我可以使用 root.getchildren 獲取所有內容,但它不允許我只返回子節點:

children = root.getchildren()
for child in children:
    ElementTree.dump(child)

有沒有獲得這些信息的好方法?

見下文

import xml.etree.ElementTree as ET
import pandas as pd

xml = '''<?xml version="1.0" encoding="UTF-8"?>
<persons>
   <person id="1" name="John">
      <city id="21" name="New York" />
   </person>
   <person id="2" name="Mary">
      <city id="22" name="Los Angeles" />
   </person>
</persons>'''

root = ET.fromstring(xml)
data = []
for p in root.findall('.//person'):
  data.append({'parson': p.attrib['name'], 'city': p.find('city').attrib['name']})
df = pd.DataFrame(data)
print(df)

output

  parson         city
0   John     New York
1   Mary  Los Angeles

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM