[英]How do i parse xml file with namespace?
我已经完成了以下编码,但不知道为什么它出现空 dataframe。
<Report xmlns="urn:crystal-reports:schemas:report-detail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:crystal-reports:schemas:report-detail http://www.businessobjects.com/products/xml/CR2008Schema.xsd">
<Details Level="1">
<Field Name='ReportNo'><Value>90</Value>
ns = {"urn:crystal-reports:schemas:report-detail#"}
def test(xml_file, df_cols):
global df
xtree = et.parse(xml_file)
xroot = xtree.getroot()
out_xml = pd.DataFrame(columns=df_cols)
for node in xroot.findall("urn:Group[1]/Details/Field", ns):
name = node.attrib.get("Name")
value = node.find("Value").text
您粘贴的 XML 代码段不符合您的查询,它缺少您要查找的<Group>
元素。
无论哪种方式,您都需要
:
,而不是全角冒号:
我在这里选择了r
(“report”的缩写)作为urn:crystal-reports:schemas:report-detail
的别名。 如果不想使用别名,也可以使用简写语法{urn:crystal-reports:schemas:report-detail}Group
等,这样就不需要命名空间 map。
所有这些都解决了,我们得到类似的东西
import xml.etree.ElementTree as et
data = """<?xml version="1.0"?>
<Report xmlns="urn:crystal-reports:schemas:report-detail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:crystal-reports:schemas:report-detail http://www.businessobjects.com/products/xml/CR2008Schema.xsd">
<Group>
<Details Level="1">
<Field Name="ReportNo"><Value>90</Value></Field>
<Field Name="Other"><Value>644</Value></Field>
</Details>
</Group>
</Report>
"""
nsmap = {"r": "urn:crystal-reports:schemas:report-detail"}
xroot = et.XML(data) # could read from file here
for node in xroot.findall("r:Group/r:Details/r:Field", nsmap):
name = node.attrib.get("Name")
value = node.find("r:Value", nsmap).text
print(name, value)
这里的 output 是
ReportNo 90
Other 644
– 将其插入 dataframe 作为练习留给读者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.