使用xml.etree.ElementTree在任何嵌套深度进行通配符搜索 [英] Wildcard search at any nested depth using xml.etree.ElementTree
问题描述
我有一组XML文件,其中包含
I have a group of XML files which contain entries like
<group name="XXX common string">
<value val="12" description="a dozen">
<text>one less than a baker's dozen</text>
</value>
<value val="13" description="a baker's dozen">
<text>One more than a dozen</text>
</value>
</group>
<group name="YYY common string">
<value val="42" description="the answer">
<text>What do you get if you multiple 6 by 9?</text>
</value>
</group>
有什么简单的方法,使用 import xml.etree.ElementTree作为ET
和
Is there any simple way, using import xml.etree.ElementTree as ET
and
parser = ET.XMLParser()
parser.parser.UseForeignDTD(True)
if (args.info) or (args.diagnostics):
print('Parsing input file : ' + inputFileName)
tree = ET.parse(inputFileName, parser=parser)
root = tree.getroot()
搜索仅< group>
元素的名称包含特定值 val
的公用字符串?
to search for only <group>
elements who#s name contains "common string" for a particular value val
?
重要:这些组嵌套在不同文件中的不同深度。
Important: these groups are nested at different depths in different files.
推荐答案
这有点困难,因为您自己的代码将不适用于您在问题中发布的
示例数据(例如,其中没有包含
字符串 error $ c的示例) $ c>,并且没有
id
属性,并且您的代码
似乎无法搜索特定的值
val
,似乎
是您的要求之一)。但是这里有一些想法...
This was a little difficult, because your own code won't work with the
example data you posted in your question (e.g., nothing there contains
the string error
, and there are no id
attributes, and your code
doesn't appear to search for "a particular value
val
, which seemed
to be one of your requirements). But here are a few ideas...
查找包含的所有
,您可以执行以下操作:组
元素 name
属性中的通用字符串
For finding all group
elements that contain common string
in the name
attribute, you could do something like this:
>>> matching_groups = []
>>> for group in tree.xpath('//group[contains(@name, "common string")]'):
... matching_groups.append[group]
...
鉴于您的样本数据将导致:
Which given your sample data would result in:
>>> print '\n'.join([etree.tostring(x) for x in matching_groups])
<group name="XXX common string">
<value val="12" description="a dozen">
<text>one less than a baker's dozen</text>
</value>
<value val="13" description="a baker's dozen">
<text>One more than a dozen</text>
</value>
</group>
<group name="YYY common string">
<value val="42" description="the answer">
<text>What do you get if you multiple 6 by 9?</text>
</value>
</group>
如果您希望将结果限制为仅个组
包含 value
元素且属性为 val
== 42
,您可以尝试:
If you wanted to limit the results to only group
elements that
contain value
element with attribute val
== 42
, you could try:
>>> matching_groups = []
>>> for group in tree.xpath('//group[contains(@name, "common string")][value/@val = "42"]'):
... matching_groups.append(group)
...
哪个会产生:
>>> print '\n'.join([etree.tostring(x) for x in matching_groups])
<group name="YYY common string">
<value val="42" description="the answer">
<text>What do you get if you multiple 6 by 9?</text>
</value>
</group>
这篇关于使用xml.etree.ElementTree在任何嵌套深度进行通配符搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!