如何在Python 2.6中使用ElementTree解析XML文件

时间:2015-10-28 03:58:34

标签: python xml-parsing

我有一个名为Enums.txt的XML文件,如下所示:

<Enums>
    <Enum name = "abc">
        <Item>Inactive</Item>
        <Item>Active</Item>
    </Enum>
    <Enum name = "xyz">
        <Item>Blocked</Item>
        <Item>Halted</Item>
    </Enum>
    <Enum name = "pqr">
        <Item>NONE</Item>
        <Item>PASS</Item>
        <Item>BLOCK</Item>
    </Enum>
</Enums>

当我在abc和pqr中的命令行标签中运行“python parseXml.py abc,pqr”时,应删除修改后的文件并将其写入新文件。

以下是我的parseXml.py:

#!/usr/bin/env python
from xml.etree import ElementTree
import sys
import commands

tree = ElementTree.parse('Enums.txt')
wanted=sys.argv[1]
wantedSet=set(wanted.strip().split(','))

for enum in root.findall('Enum'):
    name=enum.get('name')
    if name not in wantedSet:
        for child in list(enum):
            enum.remove(child)
tree.write('Enums_new.txt')

但它会出现以下语法错误。

File "parseXml.py", line 5, in <module>
    tree = ElementTree.parse('Enums.txt')
  File "/usr/lib64/python2.6/xml/etree/ElementTree.py", line 862, in parse
    tree.parse(source, parser)
  File "/usr/lib64/python2.6/xml/etree/ElementTree.py", line 586, in parse
    parser.feed(data)
  File "/usr/lib64/python2.6/xml/etree/ElementTree.py", line 1245, in feed
    self._parser.Parse(data, 0)
xml.parsers.expat.ExpatError: syntax error: line 1, column 0

有人可以帮我纠正这个错误吗?

0 个答案:

没有答案