Python:将搜索索引从xml文件打印到xml文件

时间:2014-05-15 07:49:21

标签: python xml

我编写的代码是从XML文件中找到索引我正在寻找的。我正在寻找的索引是在data.txt文件中写的。要打开data.txt文件,我已准备好代码with open("data.txt") as in_file:)... k=[int(number, 16) for number in data]。现在我只需要所有索引(在data.txt中)打印输出文件(output.xml。我想用于循环,但我现在不在。

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>

1 个答案:

答案 0 :(得分:0)

问题:ObjectDictionary.iter('Variable')实际上迭代整个节点ObjectDictionary树。您示例中Variable的匹配深度为4级(请参阅下面的xml转储)。

<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.getparent().remove(Variable)

由于代码中有许多地方需要从迭代结果中删除元素。我建议定义一个辅助函数并调用函数来完成这项工作。

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)