繁体   English   中英

将数据从 xml 提取到 Excel (Python 2.7)

[英]Extract data from xml to Excel (Python 2.7 )

我正在尝试从 XML 文件中提取一些数据并使用该信息创建一个 Excel。

XML文件:

<UniversalTransaction>
    <TransactionInfo>
        <DataContext>
            <DataSourceCollection>
                <DataSource>
                    <Type>AccountingInvoice</Type>
                    <Key>AR INV 00001006</Key>
                </DataSource>
            </DataSourceCollection>

            <Company>
                <Code>DCL</Code>
                <Country>
                    <Code>CL</Code>
                    <Name>Chile</Name>
                </Country>
                <Name>Your Chile Corp</Name>
            </Company>
...etc

然后我在python 2.7中制作了这个代码

import xml.etree.ElementTree as ET
import xlwt
from datetime import datetime

tree = ET.parse('ar.xml')
root = tree.getroot()

#extract xml
invoice = root.findall('DataSource')
arinv = root.find('Key').text
country = root.findall('Company')
ctry = root.find('Name').text

wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')

ws.write(0, 0, arinv)
ws.write(0, 1, ctry)

wb.save('example2.xls')

但我收到此错误:

arinv = root.find('Key').text
'NoneType' object has no attribute 'text' 

我想它会和

ctry = root.find('Name').text

同样,当我将代码的“extract xml”部分更改为此

for ar in root.findall('DataContext'):
    nro = []
    ctry = []
    inv = ar.find('Key').text
    nro.append(inv)
    country = ar.find('Name').text
    ctry.append(country)

我收到以下错误:

ws.write(0, 0, arinv)
name 'arinv' is not defined

再说一次,我想它与“ctry”相同

视窗 10,蟒蛇 2.7

我会感谢任何帮助,谢谢。

最好提出简短的问题 - 没有你的一堆上下文代码。 当您仔细尝试拆分确切的简短问题时,您可能会自己找到解决方案。

根据文档, Element.find基本上只能在直接孩子中找到。 您需要使用一些 XPath(查看文档中的 XPath 表达式),例如

root.findall('.//Key')[0].text

(假设密钥始终存在,包含文本并且在文档中是唯一的;即未经验证)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM