![](/img/trans.png)
[英]Python ElementTree - select element attributes based on value of 1 attribute
[英]ElementTree XPath - Select Element based on attribute
我在ElementTree中使用屬性XPath Selector時遇到問題,我應該可以根據文檔來做
這是一些示例代碼
XML
<root>
<target name="1">
<a></a>
<b></b>
</target>
<target name="2">
<a></a>
<b></b>
</target>
</root>
蟒蛇
def parse(document):
root = et.parse(document)
for target in root.findall("//target[@name='a']"):
print target._children
我收到以下例外:
expected path separator ([)
您嘗試使用的語法是ElementTree 1.3中的新增功能。
此版本隨Python 2.7或更高版本一起提供。 如果您使用的是Python 2.6或更低版本,那么您仍然可以使用ElementTree 1.2.6或更低版本。
這段代碼有幾個問題。
Python的buildin ElementTree(簡稱ET)沒有真正的XPATH支持; 只有一個有限的子集例如,它不支持像//target
這樣的從根目錄查找 。
注意: 文檔提到了“ // ”,但只針對孩子:所以表達式為.//target
是有效的; //...
不是!
還有一種替代實現: lxml更豐富。 對於內置代碼,使用文檔的接縫。 那不符合/工作。
@name
表示法選擇xml- 屬性 ; xml-tag中的key=value
表達式。
因此,名稱值必須為1或2才能選擇給定文檔中的內容。 或者,可以使用子元素 “a”搜索目標: target[a]
(no @)。
對於給定的文檔,使用內置的ElementTree(v1.3)解析為root,以下代碼是正確的並且正常工作:
root.findall(".//target")
找到兩個目標 root.findall(".//target/a")
找到兩個a元素 root.findall(".//target[a]")
這會再次找到兩個target-element,因為它們都有一個a元素 root.findall(".//target[@name='1']")
僅查找第一個目標。 請注意,需要大約1的引號; 否則會引發SyntaxError root.findall(".//target[a][@name='1']")
也有效; 找到那個目標 root.findall(".//target[@name='1']/a")
只查找一個a元素; ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.