我需要将XML文件转换为CSV文件,其中属性位于root标记内。
我检查了许多链接,但没有找到任何通过解析根标签属性将XML转换为CSV的示例。
<Products>
<Product ProductID="1234" ProductName="ABC" Category="Food" />
<Product ProductID="1236" ProductName="ABE" Category="Healthcare" />
</Products>
ProductID = member.find('Product').attrib.get('ProductID')
Product_nodes.append(ProductID)
ProductID, ProductName, Category
1234, ABC,Food
1236, ABE,Healthcare
答案 0 :(得分:1)
使用csv
和lxml
库:
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),','),'
')