pythonxml findall做n

2024-09-30 01:29:04 发布

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

我试图使用findall对一些xml元素进行选择,但是没有得到任何结果。在

import xml.etree.ElementTree as ET
import sys

storefront = sys.argv[1]

xmlFileName = 'promotions{0}.xml'

xmlFile = xmlFileName.format(storefront)

csvFileName = 'hrz{0}.csv'
csvFile = csvFileName.format(storefront)
ET.register_namespace('', "http://www.demandware.com/xml/impex/promotion/2008-01-31")
tree = ET.parse(xmlFile)

root = tree.getroot()
print('------------------Generate test-------------\n')



csv = open(csvFile,'w')
n = 0
for child in root.findall('campaign'):
    print(child.attrib['campaign-id'])
    print(n)
    n+=1

XML如下所示:

^{pr2}$

你知道我做错了什么吗? 我尝试过stackoverflow上找到的不同解决方案,但似乎没有什么对我有用(从我尝试过的东西来看)。 列表为空。 很抱歉,如果这是非常明显的事情,我是python新手。在


Tags: csvcsvfileimporttreeformatsysrootxml
1条回答
网友
1楼 · 发布于 2024-09-30 01:29:04

正如@MartijnPieters所提到的here,etree的.findall使用名称空间参数,而{}用于树的xml输出。因此,考虑使用显式前缀映射默认名称空间。以下使用doc,但甚至可以是cosmin。在

另外,考虑with和{}甚至是csv模块作为打印和CSV输出的更好的处理程序。在

import csv
...

root = tree.getroot()
print('         Generate test      -\n')

with open(csvFile, 'w') as f:
    c = csv.writer(f, lineterminator='\n')

    for n, child in enumerate(root.findall('doc:campaign', namespaces={'doc':'http://www.demandware.com/xml/impex/promotion/2008-01-31'})):
        print(child.attrib['campaign-id'])
        print(n)
        c.writerow([child.attrib['campaign-id']])

#          Generate test      -

# 10off-310781
# 0
# MNT-deals
# 1
# black-friday
# 2

相关问题 更多 >

    热门问题