将节点文本和标签从XML打印到CSV文件

时间:2016-04-15 05:35:41

标签: xml python-2.7 csv

<devices>

  <entry name="Rule 1">
    <from>
      <member>abcd</member>
    </from>
    <to>
      <member>efg</member>
    </to>
  </entry>

  <entry name="Rule 2">
    <from>
      <member>lmno</member>
    </from>
    <to>
      <member>hijk</member>
    </to>
  </entry>
</devices>

**这是我申请查找节点标签和文本**

def policy():
    with open('G:\XML-1.xml', 'rt') as f:
        tree = ET.parse(f)

    for node0 in tree.findall('.//devices//rules/entry'):
        d1 = {'rule': node0.get('name')}
        print d1
    for node1 in tree.findall('.//devices/from/member'):
        d2 = {'from': node1.text}
        print d2
    for node2 in tree.findall('.//devices//to/member'):
        d3 = {'to': node2.text}
        print d3
policy()

这是运行代码后的结果

{'rule':Rule1}
{'rule':Rule2}
{'from':abcd}
{'from':lmno}
{'to':efg}
{'to':hijk}
  1. 添加条件以在条目名称中查找更多规则。
  2. 如果添加了规则,请搜索类似的标签和文字。
  3. 在csv文件中打印,方法是按规则1,规则2组合值,如下所示

    的Rule1 A B C D EFG 规则2 LMNO HIJK

0 个答案:

没有答案