使用 Elementtree 获取特定数据形式 xml

Get specific data form xml using Elementtree

嗨,我有一个类似的 xml:

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
    <env:Header />
    <env:Body>
        <env:Fault>
            <faultcode>env:Server</faultcode>
            <faultstring>JBO-27024: Failed to validate a row with key oracle.jbo.Key[300000013314061 ] in Offer JBO-27024: Failed to validate a row with key oracle.jbo.Key[300000013314064 ] in RevenueEONon si possono aggiungere prodotti su questa Opportunit\xc3\xa0</faultstring>
            <detail>
                <tns:ServiceErrorMessage xmlns:tns="http://xmlns.tom.com/adf/svc/errors/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="tns:ServiceRowValErrorMessage">
                    <tns:code>27024</tns:code>
                    <tns:message>JBO-27024: Failed to validate a row with key oracle.jbo.Key[300000013314061 ] in Offerta_2_c</tns:message>
                    <tns:severity>SEVERITY_ERROR</tns:severity>
                    <tns:detail xsi:type="tns:ServiceRowValErrorMessage">
                        <tns:code>27024</tns:code>
                        <tns:message>JBO-27024: Failed to validate a row with key jbo.Key[300000013314064 ] in RevenueEO</tns:message>
                        <tns:severity>SEVERITY_ERROR</tns:severity>
                        <tns:detail xsi:type="tns:ServiceErrorMessage">
                            <tns:code />
                            <tns:message>Non si possono aggiungere prodotti</tns:message>/*  THIS ROW  */
                            <tns:severity>SEVERITY_ERROR</tns:severity>
                            <tns:exceptionClassName>ValidationException</tns:exceptionClassName>
                        </tns:detail>
                        <tns:exceptionClassName>oracle.jbo.RowValException</tns:exceptionClassName>
                        <tns:objectName>RevenueEO</tns:objectName>
                    </tns:detail>
                    <tns:exceptionClassName>RowValException</tns:exceptionClassName>
                    <tns:objectName>Offer</tns:objectName>
                </tns:ServiceErrorMessage>
            </detail>
        </env:Fault>
    </env:Body>
</env:Envelope>

如何从这个 XML 中检索字符串 'Non si possono aggiungere prodotti',问题是这个信息包含在标签 <tns:message> 中,在这个 XML 中有许多类似的标签。我如何使用 ElementTree 来处理这个问题,目前我使用正则表达式却收效甚微。

这有点取决于你想做什么。

第一件事是获取命名空间。在下面的示例中,我使用 detail 元素的第一个子元素来访问名称空间字典(可能有不同的方法):

all_ns = root.findall('.//detail')[0].getchildren()[0].nsmap

然后我可以使用此 for 循环遍历具有 tns 命名空间的所有消息并获取您感兴趣的消息。

for i in root.findall('.//tns:message', namespaces=all_ns):
    if 'Non si' in i.text:
        print(i.text)

但是,如果日志文件中的所有其他行都提供了有关特定错误的信息,那么理解您选择该特定行的原因会很棒。

如果您只想获取按层次顺序列出的错误(即父级 > 子级),只需 运行:

for i in root.findall('.//tns:message', namespaces=all_ns):
    print(i.text)