使用 ElementTree 解析 XML:树的根作为 XML 本身返回。我如何进一步解析它以找到一个元素?

Parsing an XML using ElementTree: The root of the tree is returned as an XML itself. How do I further parse it to find an element?

我正在使用 ElementTree 解析 XML 文件。在我的例子中,树的根作为 XML 本身返回。我如何进一步解析它以提取元素 中的文本?

tree = ETree.ElementTree(response)
print("tree:---", tree)
print("root:---", tree.getroot())
print("element found:---", tree.getroot().findall("./a:Message"))

输出

    tree:--- <xml.etree.ElementTree.ElementTree object at 0x00000>
    root:--- <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
        <s:Header>
            <o:Security s:mustUnderstand="1"
                        xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                <!-- Sample XML -->
            
            </o:Security>
        </s:Header>
        <s:Body>
            <Response xmlns="http://tempuri.org/">
                <Result xmlns:a="http://xmldataschemas.data">
                    <!-- Fields must be in this exact order.  -->
                    <a:Message>xxx Document is being processed</a:Message>
                    <a:ResponseCode>DOCUMENT_ERROR</a:ResponseCode>
                </Result>
            </Response>
        </s:Body>
    </s:Envelope>
     element found:--- None

您必须处理 xml 中的名称空间。所以试试这个:

ns = {'a': 'http://xmldataschemas.data'}
root.find('.//a:Message',ns).text

输出:

'xxx Document is being processed'