我刚开始学习 Python,必须编写一个程序来解析 xml 文件。我必须在 2 个不同的文件中找到一个名为 OrganisationReference 的标签并返回它。实际上,有多个具有此名称的标签,但只有一个,即我要返回的标签,它的 Tag OrganisationType 值为 DEALER 作为父标签(不太确定该术语是否正确)。我尝试为此使用 ElementTree。这是代码:
import xml.etree.ElementTree as ET
tree1 = ET.parse('Master1.xml')
root1 = tree1.getroot()
tree2 = ET.parse('Master2.xml')
root2 = tree2.getroot()
for OrganisationReference in root1.findall("./Organisation/OrganisationId/[@OrganisationType='DEALER']/OrganisationReference"):
print(OrganisationReference.attrib)
for OrganisationReference in root2.findall("./Organisation/OrganisationId/[@OrganisationType='DEALER']/OrganisationReference"):
print(OrganisationReference.attrib)
Run Code Online (Sandbox Code Playgroud)
但这不返回任何内容(也没有错误)。有人可以帮助我吗?
我的文件看起来像这样:
<MessageOrganisationCount>a</MessageOrganisationCount>
<MessageVehicleCount>x</MessageVehicleCount>
<MessageCreditLineCount>y</MessageCreditLineCount>
<MessagePlanCount>z</MessagePlanCount>
<OrganisationData>
<Organisation>
<OrganisationId>
<OrganisationType>DEALER</OrganisationType>
<OrganisationReference>WHATINEED</OrganisationReference>
</OrganisationId>
<OrganisationName>XYZ.</OrganisationName>
....
Run Code Online (Sandbox Code Playgroud)
由于 OrganisationReference 在这个文件中出现了几次,并且在开始和结束标签之间有不同的文本,我想得到你在第 9 行看到的那个:它有一个 OrganisationId 作为父标签,DEALER 也是一个OrganizationId 的子标签。