Question

I wrote code that from XML file find Indexes I'm looking for. That indexes I'm looking for are writen in data.txt file. To open data.txt file I all ready have code with open("data.txt") as in_file:)...k=[int(number, 16) for number in data]. now I just need to all indexes(in data.txt) print me in output file(output.xml. I was thinking to use for loop but i don't now where.

DATA.TXT:

'3001','1018','1200'

CODE:

from lxml import etree as ET
import serial as ser
tree = ET.parse('master.xml')
root = tree.getroot()


with open("data.txt") as in_file:
    data = in_file.read().strip().replace("'", "").split(",")
    k=[int(number, 16) for number in data]

for MagicNumber in root.findall('MagicNumber'):
    print MagicNumber.tag,':', MagicNumber.text
print''

for FileInfo in root.find('FileInfo'):
    print FileInfo.tag,':', FileInfo.text
print''

for DeviceInfo in root.find('DeviceInfo'):
    print DeviceInfo.tag,':', DeviceInfo.text
print''

for DummyUsage in root.find('DummyUsage'):
    print DummyUsage.tag,':', DummyUsage.text
print''

for ObjectDictionary in root.find('ObjectDictionary'):
    print ''
    print ObjectDictionary.tag,':', ObjectDictionary.get('name'), ObjectDictionary.text

    for Record in ObjectDictionary.iter('Record'):
        if Record.find('./Index').text == str(i):
            print 'Record name: ', Record.attrib['name']
        elif Record.find('./Index').text != str(i):
            ObjectDictionary.remove(Record)              

    def remove_self(target):
        target.getparent().remove(target)
    for Variable in ObjectDictionary.iter('Variable'): 
        if Variable.find('./Index').text == str(i):
            print 'Variable name: ', Variable.attrib['name']
        elif Variable.find('./Index').text != str(i):
            remove_self(Variable)

    for Array in ObjectDictionary.iter('Array'):
        if Array.find('./Index').text == str(i):
            print 'Array name: ', Array.attrib['name']
        elif Array.find('./Index').text != str(i):
            ObjectDictionary.remove(Array)

tree.write('output.xml')

XML:

<?xml version="1.0"?>
<EDSFile>
    <MagicNumber>-1616</MagicNumber>
    <FileInfo>
        <FileVersion>1</FileVersion>
        <FileRevision>0</FileRevision>
        <ModificationTime>12:19PM</ModificationTime>
    </FileInfo>
    <DeviceInfo>
        <ProductNumber>0</ProductNumber>
        <RevisionNumber>0</RevisionNumber>
        <OrderCode>Order code</OrderCode>
        <BaudRate_10>0</BaudRate_10>
        <BaudRate_20>0</BaudRate_20>
        <BaudRate_1000>0</BaudRate_1000>
        <Granularity>0</Granularity>
    </DeviceInfo>
    <DummyUsage>
        <Dummy0001>0</Dummy0001>
        <Dummy0002>1</Dummy0002>
        <Dummy0003>1</Dummy0003>
    </DummyUsage>
    <ObjectDictionary>
        <Group name="MandatoryObjects">
        </Group>
        <Group name="OptionalObjects">
            <Array name="Store Parameter Field">
                <Index>4112</Index>
                <ObjectType>8</ObjectType>
                <Variable name="Number of Entries">
                    <Index>4112</Index>
                    <Subindex>0</Subindex>
                    <DataType>5</DataType>
                    <AccessType>0</AccessType>
                    <ObjectType>7</ObjectType>
                    <DefaultValue>3</DefaultValue>
                    <PDOMapping>0</PDOMapping>
                </Variable>
                <Variable name="Save all Parameters">
                    <Index>4112</Index>
                    <Subindex>1</Subindex>
                    <DataType>7</DataType>
                    <AccessType>2</AccessType>
                    <ObjectType>7</ObjectType>
                    <PDOMapping>0</PDOMapping>
                </Variable>
                <Variable name="Save Communication Parameters">
                    <Index>4112</Index>
                    <Subindex>2</Subindex>
                    <DataType>7</DataType>
                    <AccessType>2</AccessType>
                    <ObjectType>7</ObjectType>
                    <PDOMapping>0</PDOMapping>
                </Variable>
                <Variable name="Save Application Parameters">
                    <Index>4112</Index>
                    <Subindex>3</Subindex>
                    <DataType>7</DataType>
                    <AccessType>2</AccessType>
                    <ObjectType>7</ObjectType>
                    <PDOMapping>0</PDOMapping>
                </Variable>
            </Array>
            <Variable name="COB-ID EMCY">
                <Index>4116</Index>
                <Subindex>0</Subindex>
                <DataType>7</DataType>
                <AccessType>0</AccessType>
                <ObjectType>7</ObjectType>
                <DefaultValue>$NODEID+0x80</DefaultValue>
                <PDOMapping>0</PDOMapping>
            </Variable>
            <Variable name="Inhibit Time Emergency">
                <Index>4117</Index>
                <Subindex>0</Subindex>
                <DataType>6</DataType>
                <AccessType>2</AccessType>
                <ObjectType>7</ObjectType>
                <DefaultValue>0x01F4</DefaultValue>
                <PDOMapping>0</PDOMapping>
            </Variable>
            <Variable name="Producer Heartbeat Time">
                <Index>4119</Index>
                <Subindex>0</Subindex>
                <DataType>6</DataType>
                <AccessType>2</AccessType>
                <ObjectType>7</ObjectType>
                <DefaultValue>0x000003E8</DefaultValue>
                <PDOMapping>0</PDOMapping>
            </Variable>
        </Group>
        <Group name="ManufacturerObjects">
            <Array name="Error_Log_Time_Hours_PRODUCER">
                <Index>8257</Index>
                <ObjectType>8</ObjectType>
                <Variable name="Time_Last_Error_(h)_4">
                    <Index>8257</Index>
                    <Subindex>5</Subindex>
                    <DataType>6</DataType>
                    <AccessType>0</AccessType>
                    <ObjectType>7</ObjectType>
                    <DefaultValue>0x00</DefaultValue>
                    <PDOMapping>0</PDOMapping>
                </Variable>
                <Variable name="Time_Last_Error_(h)_10">
                    <Index>8257</Index>
                    <Subindex>11</Subindex>
                    <DataType>6</DataType>
                    <AccessType>0</AccessType>
                    <ObjectType>7</ObjectType>
                    <DefaultValue>0x00</DefaultValue>
                    <PDOMapping>0</PDOMapping>
                </Variable>
                <Variable name="Time_Last_Error_(h)_20">
                    <Index>8257</Index>
                    <Subindex>21</Subindex>
                    <DataType>6</DataType>
                    <AccessType>0</AccessType>
                    <ObjectType>7</ObjectType>
                    <DefaultValue>0x00</DefaultValue>
                    <PDOMapping>0</PDOMapping>
                </Variable>
            </Array>
            <Variable name="Test_DOUT_Value">
                <Index>9229</Index>
                <Subindex>0</Subindex>
                <DataType>3</DataType>
                <AccessType>2</AccessType>
                <ObjectType>7</ObjectType>
                <DefaultValue>0</DefaultValue>
                <PDOMapping>0</PDOMapping>
            </Variable>
            <Variable name="PDO_RxLdtp2">
                <Index>9253</Index>
                <Subindex>0</Subindex>
                <DataType>3</DataType>
                <AccessType>1</AccessType>
                <ObjectType>7</ObjectType>
                <DefaultValue>0x00</DefaultValue>
                <PDOMapping>1</PDOMapping>
            </Variable>
        </Group>
        <Group name="ParametersObjects">
            <Array name="Test mode configuration">
                <Index>12319</Index>
                <ObjectType>8</ObjectType>
                <Variable name="Number of entries">
                    <Index>12319</Index>
                    <Subindex>0</Subindex>
                    <DataType>3</DataType>
                    <AccessType>0</AccessType>
                    <ObjectType>7</ObjectType>
                    <DefaultValue>9</DefaultValue>
                    <LowLimit>1</LowLimit>
                    <HighLimit>64</HighLimit>
                    <PDOMapping>0</PDOMapping>
                </Variable>
                <Variable name="Duty cycle change slope">
                    <Index>12319</Index>
                    <Subindex>7</Subindex>
                    <DataType>3</DataType>
                    <AccessType>2</AccessType>
                    <ObjectType>7</ObjectType>
                    <LowLimit>0</LowLimit>
                    <HighLimit>32767</HighLimit>
                    <PDOMapping>0</PDOMapping>
                </Variable>
                <Variable name="Stator frequency change slope">
                    <Index>12319</Index>
                    <Subindex>8</Subindex>
                    <DataType>3</DataType>
                    <AccessType>2</AccessType>
                    <ObjectType>7</ObjectType>
                    <LowLimit>0</LowLimit>
                    <HighLimit>32767</HighLimit>
                    <PDOMapping>0</PDOMapping>
                </Variable>
                <Variable name="Slip frequency change slope">
                    <Index>12319</Index>
                    <Subindex>9</Subindex>
                    <DataType>3</DataType>
                    <AccessType>2</AccessType>
                    <ObjectType>7</ObjectType>
                    <LowLimit>0</LowLimit>
                    <HighLimit>32767</HighLimit>
                    <PDOMapping>0</PDOMapping>
                </Variable>
            </Array>
        </Group>
    </ObjectDictionary>
</EDSFile>
Was it helpful?

Solution

The problem: ObjectDictionary.iter('Variable') actually iterates the whole tree of node ObjectDictionary. The matches of Variable in your example is 4 level deeper (see the xml dump below).

<Group name="OptionalObjects">
  <Array name="Store Parameter Field">
    <Index>4112</Index>
      <ObjectType>8</ObjectType>
        <Variable name="Number of Entries">
          <Index>4112</Index>
          <Subindex>0</Subindex>
          <DataType>5</DataType>
          <AccessType>0</AccessType>
          <ObjectType>7</ObjectType>
          <DefaultValue>3</DefaultValue>
          <PDOMapping>0</PDOMapping>
        </Variable>

The solution: To remove such elements, you should call Variable.getparent().remove(Variable).

As there are many places in your code need to remove elements from an iteration result. I'd suggest define a helper function and call the function to do the job.

def remove_self(target):
    target.getparent().remove(target)

# YOUR CODE
for Variable in ObjectDictionary.iter('Variable'): 
    if Variable.find('./Index').text == str(i):
        print 'Variable name: ', Variable.attrib['name']
    elif Variable.find('./Index').text != str(i):                    
        remove_self(Variable)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top