【发布时间】:2018-10-16 00:24:28
【问题描述】:
所以,我正在解析这个大小适中的 xml 文件(大约 27K 行)。不远处,我看到 ElementTree.Element 的意外行为,我在其中获得了一个条目的 Element.text,但没有获得下一个条目,但它在源 XML 中,如您所见:
<!-- language: lang-xml -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:enumeration value="24">
<xs:annotation>
<xs:documentation>UPC12 (item-specific) on cover 2</xs:documentation>
<xs:documentation>AKA item/price; ‘cover 2’ is defined as the inside front cover of a book</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="25">
<xs:annotation>
<xs:documentation>UPC12+5 (item-specific) on cover 2</xs:documentation>
<xs:documentation>AKA item/price; ‘cover 2’ is defined as the inside front cover of a book</xs:documentation>
</xs:annotation>
</xs:enumeration>
当我遇到 enumeration 标签时,我调用这个函数:
import xml.etree.cElementTree as ElementTree
...
def _parse_list_item(xmlns: str, list_id: int, itemElement: ElementTree.Element) -> ListItem:
if isinstance(itemElement, ElementTree.Element):
if itemElement.attrib['value'] is not None:
item_id = itemElement.attrib['value'] # string
if list_id == 6 and (item_id == '25' or item_id=='24'):
print(list_id, item_id) # <== debug break point here
desc = None
notes = ""
for child in itemElement:
if child.tag == (xmlns + 'annotation'):
for grandchild in child:
if grandchild.tag == (xmlns + 'documentation'):
if desc is None:
desc = grandchild.text
else:
if len(notes)>0:
notes += " " # add a space
notes += grandchild.text or ""
if item_id is not None and desc is not None:
return Codex.ListItem({'itemId': item_id, 'listId': list_id, 'description': desc, 'notes': notes})
如果我在 print 语句中放置一个断点,当我到达“24”的枚举节点时,我可以查看孙节点的文本,它们如 XML 中所示,即“UPC12...”或“AKA item ...”,但是当我到达“25”的枚举节点并查看孙子文本时,它是无。
当我通过预过滤 XML 文件删除 xs: 命名空间时,孙子文本可以正常显示。
我是否可能超出了某些大小限制或存在语法问题?
对不起,少于 pythonic 的代码,但我希望能够检查 pycharm 中的所有中间值。这是python 3.6。
感谢您提供的任何见解!
【问题讨论】:
标签: python xml python-3.x xml-parsing elementtree