请帮我在Excel中逐行显示来自xml文件的信息(每一行都有自己的来自xml的信息),结果是这样的:在KH列中,它在一行中给出了所有信息,在数字和类型中列它只给出找到的最后一个值并将其写在 Excel 中。
在屏幕上,我展示了如何处理 print(Number, Type)、print(dhdh) 和 print(page_1) 以及它是如何在 Excel 中编写的。我想逐行写下信息以及打印产生的所有信息。
Python中的代码:
from bs4 import BeautifulSoup
from pathlib import Path
import pandas as pd
file_path = r'F:\Python\XML\2'
excel_file = r'F:\Python\XML\2\2.xlsx'
page_1 = pd.DataFrame(columns = [])
for path in Path(file_path).rglob('*.XML'):
with open(path, 'r',encoding='utf-8') as parse:
xml = parse.read()
soup = BeautifulSoup(xml, features="xml")
for param in soup.find_all('num:OldNumber'):
Number = param.get('Number')
Type = param.get('Type')
print(Number, Type)
for dt in soup.find_all('PrevCadastralNumbers'):
dhdh = dt.text
print(dhdh)
Cad = {'КН':f'{dhdh}',
'Number':f'{Number}',
'Type':f'{Type}',}
page_1 = pd.concat([page_1, pd.DataFrame.from_records([Cad])], ignore_index=True, axis=0)
print(page_1)
with pd.ExcelWriter(excel_file, engine='openpyxl', mode = 'w') as writer:
page_1.to_excel(writer, sheet_name='КН',index=True)
XML 看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="EGRP_Reestr_Extract_Gkn_OKS_07_Common.xsl"?>
<KPOKS xmlns="urn://x-artefacts-rosreestr-ru/outgoing/kpoks/4.0.1" xmlns:smev="urn://x-artefacts-smev-gov-ru/supplementary/commons/1.0.1" xmlns:num="urn://x-artefacts-rosreestr-ru/commons/complex-types/numbers/1.0" xmlns:adrs="urn://x-artefacts-rosreestr-ru/commons/complex-types/address-output/4.0.1" xmlns:spa="urn://x-artefacts-rosreestr-ru/commons/complex-types/entity-spatial/5.0.1" xmlns:param="urn://x-artefacts-rosreestr-ru/commons/complex-types/parameters-oks/2.0.1" xmlns:cer="urn://x-artefacts-rosreestr-ru/commons/complex-types/certification-doc/1.0" xmlns:doc="urn://x-artefacts-rosreestr-ru/commons/complex-types/document-output/4.0.1" xmlns:flat="urn://x-artefacts-rosreestr-ru/commons/complex-types/assignation-flat/1.0.1" xmlns:ch="urn://x-artefacts-rosreestr-ru/commons/complex-types/cultural-heritage/2.0.1">
<Realty>
<Flat CadastralNumber="52:21:0000103:5144" State="06" DateCreated="2014-11-12">
<CadastralBlock>52:21:0000103</CadastralBlock>
<ObjectType>002001003000</ObjectType>
<ParentCadastralNumbers>
<CadastralNumberOKS>52:21:0000103:200</CadastralNumberOKS>
</ParentCadastralNumbers>
<PrevCadastralNumbers>
<CadastralNumber>52:21:0000103:3569</CadastralNumber>
<CadastralNumber>52:21:0000103:3591</CadastralNumber>
</PrevCadastralNumbers>
<OldNumbers>
<num:OldNumber Type="01" Number="7062" />
<num:OldNumber Type="02" Number="3651654" />
</OldNumbers>
</Flat>
</Realty>
</KPOKS>
1 个回答