在Python中过滤XML
我需要写一个过滤器,用来丢掉我XML文件中的一些元素、标签和块。下面你可以看到我的XML示例和期望的输出。我对元素、标签和属性在元素树中的区别有点困惑。我的测试没有成功!
过滤器:
import xml.etree.ElementTree as xee
def test(input):
doc=xee.fromstring(input)
print xee.tostring(doc)
#RemoveTimeStampAttribute
for elem in doc.findall('Component'):
if 'timeStamp' in elem.attrib:
del elem.attrib['timeStamp']
#RemoveTimeStampElements
for elem in doc.findall('TimeStamp'):
del elem
print xee.tostring(doc)
return xee.tostring(doc)
1 个回答
1
首先,你在删除属性的时候方法不对。你需要先检查一下 timeStamp
是否在这个元素的 attrib
字典里,然后再用 del
来删除它:
def amdfilter(input):
doc = xee.fromstring(input)
for node in doc.findall('Component'):
if 'timeStamp' in node.attrib:
del node.attrib['timeStamp']
return xee.tostring(doc)
另外,因为你这里只是在测试属性的删除,所以你需要把你的期望值改成:
expected = '<ComponentMain><Component /></ComponentMain>'
完整的测试(它通过了):
import unittest
from amdfilter import *
class FilterTest(unittest.TestCase):
def testRemoveTimeStampAttribute(self):
input = '<?xml version="1.0"?><ComponentMain><Component timeStamp="2014"></Component></ComponentMain>'
output = amdfilter(input)
expected = '<ComponentMain><Component /></ComponentMain>'
self.assertEqual(expected, output)
注意,我在这里不关心 XML 声明行(这个可以很容易地添加)。