lxml和xml名称空间-使用find和findall获取XML标签值 [英] lxml and xml namespaces - Using find and findall to get XML Tag Value

查看:75
本文介绍了lxml和xml名称空间-使用find和findall获取XML标签值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用lxml来获取and节点的文本值时,我遇到了问题,其中XML文本中包含名称空间.我使用的是findall('Status'),但结果总是为空.

I had issues in getting the text value of and nodes using lxml where the XML text has namespaces in it. I was using findall('Status') but the result was always coming to null.

最后我到达了以下工作代码....这是使用lxml来获取节点值的正确方法吗?我可以进一步改善吗?

I arrived at the following working code in the end....Is this the correct way of using lxml for fetching node values? Can i improve this further?

import lxml
xml_string='<?xml version="1.0" encoding="UTF-8"?> <SCPP:Response xmlns:SCPP="http://www.SCPP.com/XMLSchema"> <SCPP:RESP_BODY> <Seed>001335834994</Seed> </SCPP:RESP_BODY> <SCPP:RESP_HDR> <Status>00</Status> </SCPP:RESP_HDR> </SCPP:Response>'
root = etree.fromstring(xml_string)
nsmap = {}
for ns in root.xpath('//namespace::*'):
    if ns[0]:
            nsmap[ns[0]] = ns[1]

#Method 1
print 'Status is ' , root.xpath('//SCPP:RESP_HDR', namespaces=nsmap)[0].find('Status').text
print 'Seed is ' , root.xpath('//SCPP:RESP_BODY', namespaces=nsmap)[0].find('Seed').text

#Method 2
print 'Status is ' , root.findall('SCPP:RESP_HDR',namespaces=nsmap)[0].find('Status').text
print 'Seed is ' , root.findall('SCPP:RESP_BODY',namespaces=nsmap)[0].find('Seed').text

#Method 3   
print 'Status is ' , root.xpath('//SCPP:RESP_HDR', namespaces=nsmap)[0].find('Status').text
print 'Seed is ' , root.find('SCPP:RESP_BODY',namespaces=nsmap).find('Seed').text

推荐答案

您不需要手动构建 nsmap .

替换以下几行:

nsmap = {}
for ns in root.xpath('//namespace::*'):
    if ns[0]:
            nsmap[ns[0]] = ns[1]

具有:

nsmap = root.nsmap


获取特定元素文本的另一种方法(使用xpath):


Another way to get text of specific element (using xpath):

>>> root.xpath('.//SCPP:RESP_HDR/Status/text()', namespaces=nsmap)[0]
'00'
>>> root.xpath('.//SCPP:RESP_BODY/Seed/text()',namespaces=nsmap)[0]
'001335834994'

这篇关于lxml和xml名称空间-使用find和findall获取XML标签值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆