比较XML列表和python

2024-06-16 10:49:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我对XML文件进行了如下解析:

   <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE raml SYSTEM 'raml20.dtd'>
    <raml version="2.0" xmlns="raml20.xsd">
    <cmData type="actual">
        <managedObject class="LN" distName="PTR" id="2425">
          <p name="aak">220</p>
          <p name="orp">05</p>
          <p name="name">Portro</p>
          <p name="optres">false</p>
          <p name="optblu">false</p>
          <p name="aoptdet">false</p>
          <p name="advcell">false</p>
            <list name="sibList">
            <item>
              <p name="sibcity">177</p>
              <p name="sibrep">2</p>
            </item>
            <item>
              <p name="sibcity">177</p>
              <p name="sibrep">1</p>
            </item>
          </list>
         </managedObject>
       <managedObject class="LN" distName="KRNS" id="93886">
          <p name="aak">150</p>
          <p name="orp">05</p>
          <p name="name">Portro</p>
          <p name="optres">false</p>
          <p name="optblu">tru</p>
          <p name="aoptdet">false</p>
          <p name="advcell">true</p>
        <list name="sibList">
            <item>
              <p name="sibcity">177</p>
              <p name="sibrep">1</p>
            </item>
            <item>
              <p name="sibcity">180</p>
              <p name="sibrep">2</p>
            </item>
          </list>
    </menagedObject>
    ....
    <menagedObject>
    ...
    </menagedObject>
    ...
</cmData>
</raml>

我需要遍历所有menagedObject并比较所有参数(p name)。我为比较编写了代码,但我不知道如何遍历列表和比较参数。 我编写了这个函数,其中key是“p name”,value是“p name”的值:

temp = []
for i in temp_ln:
    for j, k in zip(i.getchildren(), i):
        temp.append([i.get('distName'), j.get('name'), j.text])

    tempdict = {}
    for i in temp_ln:
        td = {}
        for j in i.getchildren():
            td.update({j.get('name'): j.text})
        tempdict.update({i.get('distName'): td})

        main_dif = {}
        for key, value in tempdict.iteritems():
            dif_k = {}
            for k, v in value.iteritems():
                try: 
                    a = ref[k]
                except:
                    a = None
                if v != a:
                    if k == 'name':
                        pass
                    else:
                        dif_k.update({k:(v, a)})
            main_dif.update({key:dif_k})

Tags: nameinfalseforgetupdateitemtemp