我使用lxml包从XML读取标记和属性值。当开始标记和结束标记在一行中时,它会读取值,但当开始标记和结束标记在不同的行中时,它不会读取值。
在下面的XML中,价格标签,即<price>
和</price>
在同一行中,价格进入输出
a.xml
<catalog>
<product description="Cardigan Sweater" product_image="cardigan.jpg">
<catalog_item gender="Men's">
<cool_number>QWZ5671</cool_number>
<price></price>
</catalog_item>
</product>
</catalog>
输出:
[{'gender': ["Men's"], 'cool_number': ['QWZ5671'], 'price': ['None']}]
但如果价格标签和不同的行,那么价格就不会出现在输出中
a.xml
<catalog>
<product description="Cardigan Sweater" product_image="cardigan.jpg">
<catalog_item gender="Men's">
<cool_number>QWZ5671</cool_number>
<price>
</price>
</catalog_item>
</product>
</catalog>
输出:
[{'gender': ["Men's"], 'cool_number': ['QWZ5671']}]
两个XML的代码相同:
from lxml import etree
from collections import defaultdict
root_1 = etree.parse('a.xml').getroot()
d1= []
for node in root_1.findall('.//catalog_item'):
item = defaultdict(list)
for x in node.iter():
# iterate over the items
for k, v in x.attrib.items():
item[k].append(v)
if x.attrib is None:
item[x.attrib].append('None')
if x.text is None:
item[x.tag].append('None')
elif x.text.strip():
item[x.tag].append(x.text.strip())
d1.append(dict(item))
print(d1)
你知道当标签在不同的行中时,为什么价格标签没有出现在输出中吗? 解决这个问题的方法是什么
您的问题与此条件有关:
您正在检查标记是否包含任何文本。这里就是这种情况
<price></price>
,因为结束标记紧跟在开始标记之后。然而在这里您的标记不包含文本:换行符和一些空白字符。要解决这个问题,您必须将条件从
if x.text is None:
更改为类似if not x.text or not x.text.strip():
相关问题 更多 >
编程相关推荐