按名称获取 xml 标签内的文本

Get text inside xml tags by their name

我有一个 xml 代码,我想使用 python 语言获取精确元素(xml 标签)中的文本。

我已经尝试了几个解决方案,但没有奏效。

import xml.etree.ElementTree as ET
tree = ET.fromstring(xml)
for node in tree.iter('Model'):
print node

我该怎么做?

Xml代码:

<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <GetVehicleLimitedInfoResponse
            xmlns="http://schemas.conversesolutions.com/xsd/dmticta/v1">
            <return>
                <ResponseMessage xsi:nil="true" />
                <ErrorCode xsi:nil="true" />
                <RequestId> 2012290007705 </RequestId>
                <TransactionCharge>150</TransactionCharge>
                <VehicleNumber>GF-0176</VehicleNumber>
                <AbsoluteOwner>SIYAPATHA FINANCE PLC</AbsoluteOwner>
                <EngineNo>GA15-483936F</EngineNo>
                <ClassOfVehicle>MOTOR CAR</ClassOfVehicle>
                <Make>NISSAN</Make>
                <Model>PULSAR</Model>
                <YearOfManufacture>1998</YearOfManufacture>
                <NoOfSpecialConditions>0</NoOfSpecialConditions>
                <SpecialConditions xsi:nil="true" />
            </return>
        </GetVehicleLimitedInfoResponse>
    </soap:Body>
</soap:Envelope>

编辑和改进的答案:

import xml.etree.ElementTree as ET
import re

ns = {"veh": "http://schemas.conversesolutions.com/xsd/dmticta/v1"}

tree = ET.parse('test.xml') # save your xml as test.xml
root = tree.getroot()

def get_tag_name(tag):
    return re.sub(r'\{.*\}', '',tag)

for node in root.find(".//veh:return", ns):
    print(get_tag_name(node.tag)+': ', node.text)

它应该产生这样的东西:

ResponseMessage:  None
ErrorCode:  None
RequestId:   2012290007705 
TransactionCharge:  150
VehicleNumber:  GF-0176
AbsoluteOwner:  SIYAPATHA FINANCE PLC
EngineNo:  GA15-483936F
ClassOfVehicle:  MOTOR CAR
Make:  NISSAN
Model:  PULSAR
YearOfManufacture:  1998
NoOfSpecialConditions:  0
SpecialConditions:  None