我试图用Python解析XML文档,以便我可以对数据进行操作并写出新文件。我正在使用的完整文件是here,但这里有一段摘录:
<?xml version="1.0" encoding="UTF-8"?>
<FMPXMLRESULT xmlns="http://www.filemaker.com/fmpxmlresult">
<ERRORCODE>0</ERRORCODE>
<PRODUCT BUILD="09-11-2013" NAME="FileMaker" VERSION="ProAdvanced 12.0v5"/>
<DATABASE DATEFORMAT="M/d/yyyy" LAYOUT="" NAME="All gigs 88-07.fmp12" RECORDS="746" TIMEFORMAT="h:mm:ss a"/>
<METADATA>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Country" TYPE="TEXT"/>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Year" TYPE="TEXT"/>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="City" TYPE="TEXT"/>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="State" TYPE="TEXT"/>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Theater" TYPE="TEXT"/>
</METADATA>
<RESULTSET FOUND="746">
<ROW MODID="3" RECORDID="32">
<COL>
<DATA/>
</COL>
<COL>
<DATA>1996</DATA>
</COL>
<COL>
<DATA>Pompano Beach</DATA>
</COL>
<COL>
<DATA>FL</DATA>
</COL>
<COL>
<DATA>First Presbyterian Church</DATA>
</COL>
</ROW>
<ROW MODID="3" RECORDID="33">
<COL>
<DATA/>
</COL>
<COL>
<DATA>1996</DATA>
</COL>
<COL>
<DATA>Hilton Head</DATA>
</COL>
<COL>
<DATA>SC</DATA>
</COL>
<COL>
<DATA>Self Family Arts Center</DATA>
</COL>
</ROW>
<!-- snip many more ROW elements -->
</RESULTSET>
</FMPXMLRESULT>
最后,我想使用METADATA
字段中的信息来解析RESULTSET
中的列,但是现在我只是处理数据时遇到了麻烦。以下是我尝试获取METADATA
元素的内容:
import xml.etree.ElementTree as ET
tree = ET.parse('giglist.xml')
root = tree.getroot()
print root
metadata = tree.find("METADATA")
print metadata
打印出来:
<Element '{http://www.filemaker.com/fmpxmlresult}FMPXMLRESULT' at 0x10f982cd0>
None
为什么metadata
为空?我是否滥用了find()
方法?
答案 0 :(得分:4)
您需要处理名称空间。
但是,由于只提供了默认命名空间,您可以使用以下语法找到该元素:
import xml.etree.ElementTree as ET
ns = 'http://www.filemaker.com/fmpxmlresult'
tree = ET.parse('giglist.xml')
root = tree.getroot()
metadata = root.find("{%s}METADATA" % ns)
print metadata # prints <Element '{http://www.filemaker.com/fmpxmlresult}METADATA' at 0x103ccbe90>
以下是您可能希望看到的相关主题:
UPD(获取结果列表):
import xml.etree.ElementTree as ET
ns = 'http://www.filemaker.com/fmpxmlresult'
tree = ET.parse('giglist.xml')
root = tree.getroot()
keys = [field.attrib['NAME'] for field in root.findall(".//{%(ns)s}METADATA/{%(ns)s}FIELD" % {'ns': ns})]
results = [dict(zip(keys, [col.text for col in row.findall(".//{%(ns)s}COL/{%(ns)s}DATA" % {'ns': ns})]))
for row in root.findall(".//{%(ns)s}RESULTSET/{%(ns)s}ROW" % {'ns': ns})]
print results
打印:
[
{'City': 'Pompano Beach', 'Country': None, 'State': 'FL', 'Theater': 'First Presbyterian Church', 'Year': '1996'},
{'City': 'Hilton Head', 'Country': None, 'State': 'SC', 'Theater': 'Self Family Arts Center', 'Year': '1996'}
]