使用来自另一个文件的数据创建xml文件时出现问题

时间:2020-09-14 09:50:17

标签: python python-3.x xml xml-parsing xml.etree

我努力将数据从一个xml导出到第二个xml,但是脚本没有引发任何错误,但是什么也没有发生。.

我现在不知道该怎么办。

到XML文件的链接在这里:http://shop.dinotoys.cz/content/files/feeds/My_Product_Feed.xml

import xml.etree.ElementTree as ET 

tree = ET.parse('/home/martin/Plocha/My_Product_Feed.xml') 
  
root = tree.getroot() 

polozky = root[1]
    
data = ET.Element('hracky')

element1 = ET.SubElement(data, 'categories')
element2 = ET.SubElement(data, 'products')
    
s_elem1 = ET.SubElement(element1, 'category')
s_elem2 = ET.SubElement(element2, 'product')

category = "Dino"  
s_elem1.text = category 
    
for p in polozky.findall('Product'):
    s_elem2 = ET.SubElement(element2, 'product')
    img = p.find('MediumImage4').text
    name = p.find('DefaultTitle').text
    status = p.find('IsOrderable').text
    if status == 'True':
        status = "SKLADEM"
    else:
        status = "NENÍ SKLADEM"
    ean = p.find('EAN').text
    try:
        description = p.find('Description_1029').text
    except AttributeError:
        description = ""
        continue
    try:
        category = p.find('Item_Category_Code_Description').text
    except AttributeError:
        category = ""
        continue
    sku = p.find('Id').text
    sku_full = "D" + sku
    
    
    s_elem2_1 = ET.SubElement(s_elem2, 'name')
    s_elem2_2 = ET.SubElement(s_elem2, 'sku')
    s_elem2_3 = ET.SubElement(s_elem2, 'imgurl')
    s_elem2_4 = ET.SubElement(s_elem2, 'status')
    s_elem2_5 = ET.SubElement(s_elem2, 'ean')
    s_elem2_6 = ET.SubElement(s_elem2, 'description')
    s_elem2_7 = ET.SubElement(s_elem2, 'category')
    
    s_elem2_1.text = name
    s_elem2_2.text = sku_full
    s_elem2_3.text = img
    s_elem2_4.text = status
    s_elem2_5.text = ean 
    s_elem2_6.text = description
    s_elem2_7.text = category
    
    xml_content = ET.tostring(data)

    with open('dinoxfeed.xml', 'wb') as f:
        f.write(xml_content)
        f.close()

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

在第9行,您尝试获取名为“ hracky”的元素,但是XML文件中没有此类元素。因此数据将是一个空节点。此外,您可以遍历各种产品并进行处理,但不要触摸data变量。然后,仅导出不包含任何内容的数据变量。

另一件事是,您将每种产品的结果写入同一文件,这意味着您每次都将其覆盖,即使其余代码工作了,您在文件中也只会有最后一个产品。