使用Python非类型错误将XML解析为CSV

时间:2018-03-12 22:37:31

标签: python xml parsing

我正在尝试将XML文件解析为CSV。但是,我收到以下错误。 我用另一个简单的XML测试了逻辑,它似乎工作。我在下面提供了我的错误,XML文件,python代码和我想要的输出。现在我只添加了两个列。一直在看这几个小时,所以另一组眼睛将非常感激。谢谢!

错误:

name = member.find('CaseName').tag AttributeError: 'NoneType' object has no attribute 'tag'

XML文件:

 <?xml version="1.0" encoding="UTF-8"?>
<Nuix version="7.2.2" architecture="amd64">
  <Export
    startTime="Sun Feb 25 22:07:07 2018 (America/Chicago)"
    endTime="Sun Feb 25 22:08:03 2018 (America/Chicago)"
    exportDuration="55s"
    processingDuration="55s">

    <ExportConfiguration>

      <LoadFiles>
      </LoadFiles>

      <MessageFormat>NATIVE</MessageFormat>
      <ExportDirectory>C:\Users\KK132WQ\Desktop\Brooklyn Case - Nuix\OCR cache directory</ExportDirectory>
      <SeparateEmailAttachments>false</SeparateEmailAttachments>
      <RegenerateNatives>false</RegenerateNatives>
      <RegeneratePdfs>false</RegeneratePdfs>
      <FindTopLevelItems>false</FindTopLevelItems>
      <DescendantItems>false</DescendantItems>
      <ExportContainers>false</ExportContainers>
      <SortOrder>position</SortOrder>

      <CaseName>Brooklyn</CaseName>
      <CaseLocation>C:\Users\KK132WQ\Desktop\Brooklyn Case - Nuix</CaseLocation>

      <TimeZone>America/Chicago</TimeZone>


      <Numbering>
        <Strategy>Document ID numbering</Strategy>
        <DocumentPagesInSameFolder>true</DocumentPagesInSameFolder>
        <FamilyDocumentsInSameFolder>false</FamilyDocumentsInSameFolder>
        <FirstItemNumber>DOC-000000001</FirstItemNumber>
      </Numbering>

      <Imaging>
        <ImagingProfile>Default</ImagingProfile>
      </Imaging>

      <Naming>
        <NativeNamingScheme>Page only</NativeNamingScheme>
        <PdfNamingScheme>Page only</PdfNamingScheme>
      </Naming>
      <OcrSettings>
          <Recognition>High Quality - Slow</Recognition>
          <Deskewed/>
          <UpdateTextStore append="true"/>
          <Rotation>Auto</Rotation>
          <Languages>English</Languages>
      </OcrSettings>

      <ResemblanceThreshold>0.85</ResemblanceThreshold>

    </ExportConfiguration>

    <ExportStatistics>
      <SelectedItems>4</SelectedItems>
      <ExcludedCount>0</ExcludedCount>
      <TotalItemsToExport>4</TotalItemsToExport>
      <FailedItems>0</FailedItems>
      <DocumentNumbers>
        <First></First>
        <Last></Last>
      </DocumentNumbers>
    </ExportStatistics>

    <ExportStageDetails>
      <Stage
        name="WORK_QUEUE"
        successfulItems="4"
        failedItems="0"
        duration="1s">

        <SlipsheetItemDetails>
        </SlipsheetItemDetails>

        <FailedItemDetails>
        </FailedItemDetails>
      </Stage>
      <Stage
        name="NATIVE"
        successfulItems="4"
        failedItems="0"
        duration="33s">

        <SlipsheetItemDetails>
        </SlipsheetItemDetails>

        <FailedItemDetails>
        </FailedItemDetails>
      </Stage>
      <Stage
        name="STORED_EMAIL_FIXUP"
        successfulItems="4"
        failedItems="0"
        duration="1s">

        <SlipsheetItemDetails>
        </SlipsheetItemDetails>

        <FailedItemDetails>
        </FailedItemDetails>
      </Stage>
      <Stage
        name="PDF"
        successfulItems="4"
        failedItems="0"
        duration="1s">

        <SlipsheetItemDetails>
        </SlipsheetItemDetails>

        <FailedItemDetails>
        </FailedItemDetails>
      </Stage>
      <Stage
        name="BINARY_STORE"
        successfulItems="0"
        failedItems="0"
        duration="0s">

        <SlipsheetItemDetails>
        </SlipsheetItemDetails>

        <FailedItemDetails>
        </FailedItemDetails>
      </Stage>
      <Stage
        name="OCR_INITIALISATION"
        successfulItems="4"
        failedItems="0"
        duration="0s">

        <SlipsheetItemDetails>
        </SlipsheetItemDetails>

        <FailedItemDetails>
        </FailedItemDetails>
      </Stage>
      <Stage
        name="OCR"
        successfulItems="4"
        failedItems="0"
        duration="17s">

        <SlipsheetItemDetails>
        </SlipsheetItemDetails>

        <FailedItemDetails>
        </FailedItemDetails>
      </Stage>
      <Stage
        name="POST_OCR"
        successfulItems="4"
        failedItems="0"
        duration="0s">

        <SlipsheetItemDetails>
        </SlipsheetItemDetails>

        <FailedItemDetails>
        </FailedItemDetails>
      </Stage>
      <Stage
        name="TEXT_REPLACEMENT"
        successfulItems="4"
        failedItems="0"
        duration="1s">

        <SlipsheetItemDetails>
        </SlipsheetItemDetails>

        <FailedItemDetails>
        </FailedItemDetails>
      </Stage>
    </ExportStageDetails>

    <FileStatistics>
      <NativeFilesExported>3</NativeFilesExported>
      <NativeFilesFromStore>0</NativeFilesFromStore>
      <NativeFilesExportedInline>0</NativeFilesExportedInline>
      <NativeFilesExportedParallel>3</NativeFilesExportedParallel>
      <NativeFilesExportedParallelLocal>0</NativeFilesExportedParallelLocal>
      <NativeFilesWithInvalidTimes>0</NativeFilesWithInvalidTimes>
      <NativePlaceHolderFilesExported>0</NativePlaceHolderFilesExported>
      <NativeFilesRegenerated>0</NativeFilesRegenerated>
      <TextFilesExported>0</TextFilesExported>
      <TextPlaceHolderFilesExported>0</TextPlaceHolderFilesExported>
      <PdfFilesExported>0</PdfFilesExported>
      <PdfFilesStamped>0</PdfFilesStamped>
      <TiffFilesExported>0</TiffFilesExported>

      <PdfDetails>
        <PdfFilesFromStore>0</PdfFilesFromStore>
        <PdfFilesRegenerated>0</PdfFilesRegenerated>
        <PdfFilesExportedInline>0</PdfFilesExportedInline>
        <PdfFilesExportedParallel>0</PdfFilesExportedParallel>
        <PdfFilesExportedParallelLocal>0</PdfFilesExportedParallelLocal>
        <UserImportedPdfs>0</UserImportedPdfs>
        <PrintedPdfs>0</PrintedPdfs>
        <UnformattedTextPdfs>0</UnformattedTextPdfs>
        <ItemEncryptedPdfs>0</ItemEncryptedPdfs>
        <UnprintableItemPdfs>0</UnprintableItemPdfs>
      </PdfDetails>
    </FileStatistics>

    <PageCountStatistics>
      <PdfPages>0</PdfPages>
      <StampedPages>0</StampedPages>
      <FailedStampedPages>0</FailedStampedPages>
      <AveragePageCount>0.0</AveragePageCount>
    </PageCountStatistics>

    <ThroughputStatistics>
      <NativeDocRate>0.0857363321997085</NativeDocRate>
      <PdfDocRate>0.0</PdfDocRate>
      <StampedDocRate>0.0</StampedDocRate>
      <PdfPageRate>0.0</PdfPageRate>
      <StampingPageRate>0.0</StampingPageRate>
    </ThroughputStatistics>

    <MimeTypeStatistics>
      <MimeTypes>
        <MimeType name="application/pdf" count="4" />
      </MimeTypes>
    </MimeTypeStatistics>

  </Export>
</Nuix>

Python代码:

    import xml.etree.ElementTree as ET
    import csv

    tree = ET.parse('D:\\Users\\eferse\\Desktop\\XML_parsing\\summary-report.xml')
    root = tree.getroot()

    # open a file for writing

    Resident_data = open('D:\\Users\\eferse\\Desktop\\XML_parsing\\Nuix Export XML Parse_PythonOutput.csv', 'w')

    # create the csv writer object

    csvwriter = csv.writer(Resident_data)
    resident_head = []

    count = 0
    for member in root.findall('Export'):
        resident = []
        address_list = []
        if count == 0:
            name = member.find('CaseName').tag
            resident_head.append(CaseName)
            location= member.find('CaseLocation').tag
            resident_head.append(CaseLocation)

            csvwriter.writerow(resident_head)
            count = count + 1

        name = member.find('CaseName').text
        resident.append(CaseName)
        location= member.find('CaseLocation').text
        resident.append(CaseLocation)


        csvwriter.writerow(resident)
    Resident_data.close()

期望的输出: Output

1 个答案:

答案 0 :(得分:1)

我使用索引来访问有问题的子元素。有时,当您知道信息的位置时,这更容易做到。

您可以使用以下

进行检查
for child in root[0]:
    print(child.tag, child.attrib)

您可以根据需要继续浏览root[0][0][1]等等

您必须记住索引是父级,并且您正在寻找孩子。在您的情况下,root Nuix将返回此实例中的子项Export

root[0]是“导出”,find会搜索孩子并返回您想要的ExportConfiguration内容,而这里是您要查找的内容CaseName和{ {1}} ..

如果你这样做

CaseLocation

这将打印for child in root[0][0]: print(child.tag, child.attrib) 等标签,但您无法在此级别使用查找。您将在CaseName内搜索CaseName

一旦你有父母,你就能更容易找到孩子。

此代码有效。

我已将空列表排除在循环之外。

我还更改了CaseName值,因为它们没有变量,只有字符串名称...我还缩进了一些附加内容,因为它们不在循环中。

我已将append语句留在其中,以便您可以看到正在发生的事情。

print

CSV数据文件如下所示:

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('summary-report.xml')
root = tree.getroot()

Resident_data = open('Parse_PythonOutput.csv', 'a')

    # create the csv writer object

csvwriter = csv.writer(Resident_data)
resident_head = []
resident = []
address_list = []

count = 0
for member in root[0]:
    if count == 0:

        name = member.find('CaseName').tag
        print(name)
        resident_head.append(name)

        location = member.find('CaseLocation').tag
        print(location)
        resident_head.append(location)

        csvwriter.writerow(resident_head)
        count = count + 1

        name_text = member.find('CaseName').text
        print(name_text)
        resident.append(name_text)

        text_location = member.find('CaseLocation').text
        print(text_location)
        resident.append(text_location)

        print(resident)

csvwriter.writerow(resident)

Resident_data.close()