我整个上午都在为这件事苦苦挣扎,但一直没能让它发挥作用。在
我有这样一个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()
试试这个:
<attribute4>
是一个XML元素,而不是XML属性。因此,我首先尝试使用以下XPath:*)注意:“第一级节点”不是有效的XML元素示例,因为它包含空格
更新:
在XML示例的上下文中,}的子级:
^{pr2}$child
变量已经指向<First_Level_Node>
,它是{因此,您需要从XPath中删除
First_Level_Node
:相关问题 更多 >
编程相关推荐