首页 > 解决方案 > 如何使用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 或任何其他可能的方法更改根目录

标签: pythonxmlelementtree

解决方案


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.


推荐阅读