我的XML有问题。我要做的是连接从XML示例
中提取的列表中的值<?xml version="1.0" encoding="UTF-8"?>
<locales>
<api-url>url</api-url>
<locale>
<market>AE</market>
<languages>
<language>ar</language>
</languages>
</locale>
<locale>
<market>AM</market>
<languages>
<language>hy</language>
<language>ru</language>
</languages>
</locale>
我做的是。
inputXml = lxml.etree.parse('xml')
market = inputXml.xpath('//locale/market/text()')
Lang = inputXml.xpath('//locale[i]/languages//language/text()')
我必须连接市场和Lang这样的价值 - &gt; AE_ar,AM_hy,AM_ru
我尝试了for循环,但它没有为我锻炼。我变得像AE_ar,AE_ar,AE_ar, AM_hy,AM_hy,AM_hy
。还有另一种方法,比如使用Xslt或其他方法在Python中执行此操作
答案 0 :(得分:5)
import lxml.etree as ET
import io
content='''\
<?xml version="1.0" encoding="UTF-8"?>
<locales>
<api-url>url</api-url>
<locale>
<market>AE</market>
<languages>
<language>ar</language>
</languages>
</locale>
<locale>
<market>AM</market>
<languages>
<language>hy</language>
<language>ru</language>
</languages>
</locale>
</locales>
'''
inputXml=ET.parse(io.BytesIO(content))
for locale in inputXml.xpath('//locale'):
market = locale.xpath('market/text()')[0]
for lang in locale.xpath('languages/language/text()'):
print('{m}_{l}'.format(m=market,l=lang))
产量
AE_ar
AM_hy
AM_ru