我已经完成了编码,但不知道为什么会出现空数据。
<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发布于 2019-11-13 14:25:54
您粘贴的XML片段不符合您所拥有的查询,它缺少您要查找的<Group>元素。
不管怎样,你都需要
我在这里选择了r (“report”的缩写)作为urn:crystal-reports:schemas:report-detail的别名。如果不想使用别名,也可以使用长语法{urn:crystal-reports:schemas:report-detail}Group等,在这种情况下不需要名称空间映射。
所有的修正,我们得到的东西就像
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)这里的输出是
ReportNo 90
Other 644-把它插入数据框是留给读者的练习。
https://stackoverflow.com/questions/58838993
复制相似问题