【问题标题】:Get text inside xml tags by their name按名称获取 xml 标签内的文本
【发布时间】:2020-12-29 11:29:38
【问题描述】:

我有一个 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>

【问题讨论】:

  • 预期的输出究竟是什么?在您正在寻找entry 的代码中,但XML 文档中没有这样的元素。请改用tree.iter()
  • @mzjn 示例:MOTOR CAR 我需要获取开始标签和结束标签之间的文本。在这种情况下,输出必须是 MOTOR CAR
  • @GHOSTH4CK3R 看看我发布的答案,你可以在循环中使用 if 语句过滤掉你想要的结果!

标签: python python-3.x xml xml.etree


【解决方案1】:

编辑和改进的答案:

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

【讨论】:

  • 我已经删除了我声称 XML 没有很好命名空间的 cmets。我不是专家,如果其他人觉得一切都很好,那就这样吧。
  • 你并不需要这个函数;只需将最后一行更改为print(node.tag.split('}')[1],": ",node.text)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多