在 ElementTree 中使用 XPath 查找嵌套元素
Using XPath in ElementTree to find Nested Elements
给定以下 xml 示例,我如何打印 Actor 名称及其位置?
我希望输出为:
约翰·克里斯
俄亥俄州
艾力克
科罗拉多
<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
xmlns="http://people.example.com">
<actor>
<name>John Cleese</name>
<fictional:character>Lancelot</fictional:character>
<fictional:character>Archie Leach</fictional:character>
<Location>
<State>
<name>Ohio</>
</State>
</Location>
</actor>
<actor>
<name>Eric Idle</name>
<fictional:character>Sir Robin</fictional:character>
<fictional:character>Gunther</fictional:character>
<fictional:character>Commander Clement</fictional:character>
<Location>
<State>
<name>Colorado</>
</State>
</Location>
</actor>
</actors>
我试过下面的代码,但它只打印演员的名字,不打印州名
import xml.etree.ElementTree as ET
tree = ET.parse('Actors.xml')
root = tree.getroot()
root = fromstring(xml_text)
for actor in root.findall('{http://people.example.com}actor'):
name = actor.find('{http://people.example.com}name')
print(name.text)
for state in actor.findall('{http://characters.example.com}state'):
print(' |-->', state.text)
这样试试:
actors = root.findall('.//{*}actor')
for actor in actors:
name = actor.find('./{*}name')
location = actor.find('./{*}Location//{*}name')
print(name.text, location.text)
输出:
John Cleese Ohio
Eric Idle Colorado
给定以下 xml 示例,我如何打印 Actor 名称及其位置?
我希望输出为:
约翰·克里斯 俄亥俄州 艾力克 科罗拉多
<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
xmlns="http://people.example.com">
<actor>
<name>John Cleese</name>
<fictional:character>Lancelot</fictional:character>
<fictional:character>Archie Leach</fictional:character>
<Location>
<State>
<name>Ohio</>
</State>
</Location>
</actor>
<actor>
<name>Eric Idle</name>
<fictional:character>Sir Robin</fictional:character>
<fictional:character>Gunther</fictional:character>
<fictional:character>Commander Clement</fictional:character>
<Location>
<State>
<name>Colorado</>
</State>
</Location>
</actor>
</actors>
我试过下面的代码,但它只打印演员的名字,不打印州名
import xml.etree.ElementTree as ET
tree = ET.parse('Actors.xml')
root = tree.getroot()
root = fromstring(xml_text)
for actor in root.findall('{http://people.example.com}actor'):
name = actor.find('{http://people.example.com}name')
print(name.text)
for state in actor.findall('{http://characters.example.com}state'):
print(' |-->', state.text)
这样试试:
actors = root.findall('.//{*}actor')
for actor in actors:
name = actor.find('./{*}name')
location = actor.find('./{*}Location//{*}name')
print(name.text, location.text)
输出:
John Cleese Ohio
Eric Idle Colorado