在python中,如何提取XML的一部分

在python中,如何提取XML的一部分,python,python-3.x,xml,Python,Python 3.x,Xml,给出下面的XML <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> &

给出下面的XML

<soap:Envelope
        xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <soap:Body>
                <A>
                    <B>
                        <Id>55</Id>
                        <Name>My Name</Name>
                    </B>
                </A>
        </soap:Body>
</soap:Envelope>                
但这只给了我标签本身:

<Element 'B' at 0x10b7aa590>  

尝试以下方法:

from lxml import etree

bee = """your xml above"""    
doc = etree.fromstring(bee)
target = doc.xpath('//B')
print(etree.tostring(target[0]).decode())
将显示
r
包含您想要的所有内容

要直接获取B元素,您可以尝试

for b in root.iterfind('.//B'):
    print(ET.tostring(b))

print(ET.tostring(r))
将显示
r
包含您想要的所有内容。谢谢@JustinEzequiel,
r=root[0][0][0]
是检索“B”部分的正确方法吗?或者我可以键入B元素的名称吗?不确定您想要什么,但您可以尝试:
在root.iterfind('.//B'):print(ET.tostring(B))
@JustinEzequiel您可以将您的第一条注释转换为答案,我会接受它。
from lxml import etree

bee = """your xml above"""    
doc = etree.fromstring(bee)
target = doc.xpath('//B')
print(etree.tostring(target[0]).decode())
print(ET.tostring(r))
for b in root.iterfind('.//B'):
    print(ET.tostring(b))