当XML开始标记和结束标记位于不同的行中时,lxml不会读取它们

2024-10-05 11:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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)

你知道当标签在不同的行中时,为什么价格标签没有出现在输出中吗? 解决这个问题的方法是什么


Tags: 标记nonenumber价格标签xmlproductitem
1条回答
网友
1楼 · 发布于 2024-10-05 11:28:36

您的问题与此条件有关:

if x.text is None:
  item[x.tag].append('None')

您正在检查标记是否包含任何文本。这里就是这种情况<price></price>,因为结束标记紧跟在开始标记之后。然而在这里

...
     <price>
     </price>
...

您的标记包含文本:换行符和一些空白字符。要解决这个问题,您必须将条件从if x.text is None:更改为类似if not x.text or not x.text.strip():

相关问题 更多 >

    热门问题