[英]How to convert XML to CSV when attributes are inside the root tag?
我需要將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
使用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()
如果您可以訪問XQuery或XPath 2.0+,
string-join(//Product/string-join((@ProductID, @ProductName, @Category),','),'
')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.