python - 如何使用Python获取XML文件中child->child->child->child的内容
问题描述
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.056.001.01" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<FIToFIPmtCxlReq>
<Assgnmt>
<Id>TEST-ISO-81</Id>
<Assgnr>
<Agt>
<FinInstnId>
<BIC>CCCCGB2L</BIC>
</FinInstnId>
</Agt>
</Assgnr>
<Assgne>
<Agt>
<FinInstnId>
<BIC>MMMMGB2L</BIC>
</FinInstnId>
</Agt>
</Assgne>
<CreDtTm>2009-03-24T11:22:59</CreDtTm>
</Assgnmt>
<TxInf>
<CxlId>103012345</CxlId>
<Case>
<Id>ISO_TEST_CASE</Id>
<Cretr>
<Agt>
<FinInstnId>
<BIC>MMMMGB2L</BIC>
</FinInstnId>
</Agt>
</Cretr>
</Case>
</TxInf>
</Undrlyg>
</FIToFIPmtCxlReq>
</Document>
在这里,我想获取“TxInf”的内容,就像它的所有孩子和孩子的孩子以及数据一样。
我试过的是:
import xml.etree.ElementTree as ET
from xml.etree import ElementTree
tree = ET.parse('R3-CAMT.056.001.07-ISO-V.XML')
root = tree.getroot()
for element in root.iter():
if element.tag == "{urn:iso:std:iso:20022:tech:xsd:camt.056.001.01}TxInf":
tree._setroot(element.tag)
print(root.tag)
print(root.attrib)
请建议我是否可以使用 _setroot 或任何其他可能的方法更改根目录
解决方案
Try something along these lines on your code to see if it works:
for r in root.findall(".//*"):
if 'TxInf' in r.tag:
print(ET.tostring(r))
By the way, it may be easier to do it with lxml, if you can use it.
推荐阅读
- grafana - 如何找到用于导出 JSON 的 Grafana 版本?
- scrapy - Scrapy 安装错误:[CondaEnvironmentNotFoundError]:找不到环境:base
- c# - JSON.net 反序列化对象嵌套数据
- javascript - 如何清除 .zip 队列?
- javascript - 返回包含条件的数组的长度
- python - Django 仅在同一日期有多个公司交易的情况下查询交易
- java - SnakeYaml“找不到属性错误”
- javascript - Web 推送通知(使用服务工作者)
- javascript - 使用 fetch API 通过 formData 传递表单上输入的所有值的问题
- r - 在excel中保留几列中的匹配行