简体   繁体   中英

How to properly find an index of a list ElementTree element

I am wanting to find a specific sub element in the root list, in this case, LocationSalesDetail. After printing a list of the root of the tree, you can see there are a bunch of instances of LocationSalesDetail, but when I try to pull them in an index, it say's it can't be found. I've looked through documentation and can't see exactly what it is that I'm doing wrong, although i'm sure it's ridiculously simple.

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

print(list(root))
list(root).index('LocationSalesDetail')

tree.write('test2.xml')

恼人的

For reference, the rough XML structure for the test.xml is as follows:

<SalesTransactions>
-->CompanyNumber
-->SendingSystem
-->LocationSalesDetail
---->InvoiceNumber
---->InvoiceInformation
-->LocationSalesDetail
---->InvoiceNumber
---->InvoiceInformation
-->LocationSalesDetail
---->InvoiceNumber
---->InvoiceInformation

Because your XML file structure is not clear and what exactly you search for, if you ask for index? I create Line numer and list number for an index . I assume your XML file looks similar like this - INPUT:

<?xml version="1.0" encoding="utf-8"?>
<SalesTransactions>
  <CompanyNumber>my_customer</CompanyNumber>
  <SendingSystem>
    <LocationSalesDetail name="DE">
      <InvoiceNumber>1</InvoiceNumber>
      <InvoiceInformation>A</InvoiceInformation>
    </LocationSalesDetail>
    <LocationSalesDetail name="UK">
      <InvoiceNumber>2</InvoiceNumber>
      <InvoiceInformation>B</InvoiceInformation>
    </LocationSalesDetail>
    <LocationSalesDetail name="US">
      <InvoiceNumber>3</InvoiceNumber>
      <InvoiceInformation>C</InvoiceInformation>
    </LocationSalesDetail>
  </SendingSystem>
</SalesTransactions>

Than you can create a list of tuples with enumerate() :

import xml.etree.ElementTree as ET

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

Location_list = root.findall('.//LocationSalesDetail')

line_No = enumerate(root.iter())
for line in line_No:
    #print(line[0], line[1].tag)
    if line[1].tag =="LocationSalesDetail":
        print(line[1].tag, "   Line No:",line[0], line[1].get('name'))

print('\n')
for elem in enumerate(Location_list):
    print("List No:", elem[0], elem[1].get('name'))
    
print('\n')
# ET.dump(root)

Output:

LocationSalesDetail    Line No: 3 DE
LocationSalesDetail    Line No: 6 UK
LocationSalesDetail    Line No: 9 US


List No: 0 DE
List No: 1 UK
List No: 2 US

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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