当属性位于根标记内时,如何将XML转换为CSV?

时间:2019-03-28 09:40:58

标签: python xml csv root

我需要将XML文件转换为CSV文件,其中属性位于root标记内。

我检查了许多链接,但没有找到任何通过解析根标签属性将XML转换为CSV的示例。

XML示例:

<Products>
<Product ProductID="1234" ProductName="ABC" Category="Food" />
<Product ProductID="1236" ProductName="ABE" Category="Healthcare" />
</Products>

Python代码(出现NoneType错误):

ProductID = member.find('Product').attrib.get('ProductID')
Product_nodes.append(ProductID) 

CSV文件中的预期结果:

ProductID, ProductName, Category
1234, ABC,Food
1236, ABE,Healthcare

2 个答案:

答案 0 :(得分:1)

使用csvlxml库:

import csv

from lxml import etree


xml_content = """<Products>
<Product ProductID="1234" ProductName="ABC" Category="Food" />
<Product ProductID="1236" ProductName="ABE" Category="Healthcare" />
</Products>"""

outfile = "products.csv"
field_names = ["ProductID", "ProductName", "Category"]
root_node = etree.fromstring(xml_content)

filehandle = open(outfile, "w", newline="")
writer = csv.DictWriter(filehandle, fieldnames=field_names)
writer.writeheader()
for node in root_node.findall("Product"):
    writer.writerow(dict(node.attrib))
filehandle.close()

答案 1 :(得分:0)

如果您可以访问XQuery或XPath 2.0+,则很简单

string-join(//Product/string-join((@ProductID, @ProductName, @Category),','),'&#xa;')