How to use LXML and XPath to retrieve all child nodes in a single query

This is my xml data



New York
non-capital



London
capital

Use lxml&Python

from lxml import etree as ET

parser = ET.XMLParser(recover=True)

tree = ET.fromstring(xml_data,parser)
print (tree.xpath('//city//name/text() | //city//type/text()'))

The above code works but I want to describe the nested array as ( [‘New York’,’non-capital’],[‘London’,’capital’]]

What is an accurate xpath query/query/loop combination to get the above content?

This is one possible way:

.......
result = []
for city in tree.xpath('//city'):
result.append([city.find ('name').text, city.find('type').text])

print(result)
# output :
#[[' New York' ,'non-capital'], ['London','capital']]

This is my xml data

< /p>



New York
non-capital



London
capital

Use lxml&Python

from lxml import etree as ET

parser = ET.XMLParser(recover=True)< br />
tree = ET.fromstring(xml_data,parser)
print(tree.xpath('//city//name/text() | //city//type/text()' ))

The above code works but I want to describe the nested array as [[‘New York’,’non-capital’],[‘London’,’capital’]]

< p>What is the accurate xpath query/query/loop combination to get the above content?

This is a possible way:

....... 
result = []
for city in tree.xpath('//city'):
result.append([city.find('name').text, city.find( 'type').text])

print(result)
# output :
#[[' New York','non-capital'], ['London' ,'capital']]

Leave a Comment

Your email address will not be published.