使用Python2.7和XMLElemen在XML中选择具有特定元素值的节点

2024-06-16 11:48:27 发布

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

我整个上午都在为这件事苦苦挣扎,但一直没能让它发挥作用。在

我有这样一个XML(精简的匿名版本):

<?xml version="1.0" encoding="UTF-8"?>
<Root>
  <First_Level_Node>
    <Element_Name>
      <attribute1>1</attribute1>
      <attribute2>2</attribute2>
      <attribute3>3</attribute3>
      <attribute4>4</attribute4>
      <attribute5>5</attribute5>
      <attribute6>6</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>42</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random value</attribute5>
      <attribute6>18th Jun 2014  07:09:18 GMT</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>42</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random</attribute5>
      <attribute6>23rd Jul 2014  02:47:10 GMT</attribute6>
    </Element_Name>
    <Element_Name>
      <attribute1>42</attribute1>
      <attribute2></attribute2>
      <attribute3>NO</attribute3>
      <attribute4>42</attribute4>
      <attribute5>random</attribute5>
      <attribute6>08th Nov 2014  23:53:31 GMT</attribute6>
    </Element_Name>
  </First_Level_Node>
</Root>

现在我已经从所有元素中获取一些值并使用它们。在

但是现在我只想选择具有特定属性值对的元素。在

例如,在我粘贴的xml中,我只需要获取attribute4=42的元素

我目前的代码如下:

^{pr2}$

但是我在ch中没有得到任何值,我尝试了相同的多个变体以及我所知道的所有Xpath,仍然没有结果。在

任何帮助都将不胜感激。在

注意:元素名称是动态的,可以更改。在

编辑:尝试了这个,但我得到了错误的信息作为输出。在

for slot in input_data:
        for child in root[0]:
            for ch in child:
                if ch.text == '42' and ch.tag == "attribute4":
                    flag=1
                if ch.tag == slot and flag == 1:
                    flag=0
                    if ch.text == 'UNCOMPUTED' or ch.text == None:
                        slot_text.append("Undefined")
                    else:
                        slot_text.append(ch.text)
        data[slot]=Counter(slot_text).most_common()

Tags: notextname元素randomelementchslot
2条回答

试试这个:

tree=ET.parse('xmlname.xml')
root=tree.getroot()

for first_level_node in root:
    for element_name in first_level_node:
        for attribute in element_name:
            if attribute.tag == "attribute4" and attribute.text == "42":
            # do something

<attribute4>是一个XML元素,而不是XML属性。因此,我首先尝试使用以下XPath:

.....
xpath = 'First Level Node/*[attribute4="' + str(sys.argv[1]) + '"]'
for ch in child.findall(xpath):
......

*)注意:“第一级节点”不是有效的XML元素示例,因为它包含空格

更新:

在XML示例的上下文中,child变量已经指向<First_Level_Node>,它是{}的子级:

^{pr2}$

因此,您需要从XPath中删除First_Level_Node

.....
xpath = '*[attribute4="' + str(sys.argv[1]) + '"]'
for ch in child.findall(xpath):
......

相关问题 更多 >