Python如何计算具有限制值的XML属性元素

2024-04-25 08:40:41 发布

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

我试图只计算代码属性大于或等于10的文件标记。下面是我的代码:-在

from xml.dom.minidom import parse, parseString
import xml.dom.minidom

DOMTree = xml.dom.minidom.parse("param.xml")
group = DOMTree.documentElement

code_line_10=[0,1,2,3,4,5,6,7,8,9]

num_source_file = 0
for file in group.getElementsByTagName("file"):
    if file.hasAttribute("code"):
         attribute_value = file.getAttribute("code")
         if attribute_value not in code_line:
             num_source_file += 1
print(num_source_file)

这是我使用:-在

^{pr2}$

在执行上述代码时,它将计算xml文档中的所有文件标记,包括我要排除的那些。我在做什么我做的不对?在


Tags: 文件代码标记importsourceparselinegroup
3条回答

getAttribute以字符串形式返回值。尝试类似于:

...    
attribute_value = file.getAttribute("code")
    if int(attribute_value) <= 10:
...

使用支持xpath的库,如lxml,然后可以执行以下操作:

from lxml import etree
tree = etree.parse("param.xml")
print len(tree.getroot().xpath("//file[not(@code>0 and @code<10)]"))

file.getAttribute("code")返回str对象,'1' in [1]False。现在有多种方法可以解决你的问题。在

首先是坏的解决方案:

  • code_line_10=[0,1,..,9]替换为code_line_10=['0','1',..,'9']。在
  • if attribute_value not in code_line:更改为if int(attribute_value) not in code_line:(注意,如果代码属性不能转换为int,则会引发异常)

在这两种解决方案中,算法仍然需要遍历列表中的所有项目,并逐个比较这些项目,这需要一些时间。更快的解决方案是将值与运算符<=进行比较。因此可以将if替换为if int(attribute_value) >= 10:(同样,如果代码属性不能转换为int,则会引发异常)

相关问题 更多 >