我能够获取图像标签中的值(请参见下面的XML),但不能获取类别标签中的值。区别在于一个是CDATA部分,另一个只是一个字符串。任何帮助将不胜感激。
from xml.dom import minidom
xml = """<?xml version="1.0" ?>
<ProductData>
<ITEM Id="0471195">
<Category>
<![CDATA[Homogenizers]]>
</Category>
<Image>
0471195.jpg
</Image>
</ITEM>
<ITEM Id="0471195">
<Category>
<![CDATA[Homogenizers]]>
</Category>
<Image>
0471196.jpg
</Image>
</ITEM>
</ProductData>
"""
bad_xml_item_count = 0
data = {}
xml_data = minidom.parseString(xml).getElementsByTagName( ProductData )
parts = xml_data[0].getElementsByTagName( ITEM )
for p in parts:
try:
part_id = p.attributes[ Id ].value.strip()
except(KeyError):
bad_xml_item_count += 1
continue
if not part_id:
bad_xml_item_count += 1
continue
part_image = p.getElementsByTagName( Image )[0].firstChild.nodeValue.strip()
part_category = p.getElementsByTagName( Category )[0].firstChild.data.strip()
print .join([part_id, part_category, part_image])