转换 ReadyAPI xpath 以在 Python 3 中使用

问题描述

我在将 ReadyAPI 中使用的 xpath 表达式转换为在 Python 3 中使用 lxml 库时遇到问题。我已经阅读了 lxml 文档,但没有得到相同的结果。

这是我的 XML:

<Envelope>
    <Body>
        <ReplyResponses>
            <RepyResults>
                <Reply>
                    <ContentsofReply>
                        <Content>
                            <IDofContent>ID of Content 1</IDofContent>
                        </Content>
                    </ContentsofReply>
                    <ID>ID of Reply 1</ID>
                    <Name>Name of Reply</Name>
                </Reply>
            </RepyResults>
        </ReplyResponses>
    </Body>
</Envelope>

我在 ReadyAPI 中使用以下 xpath 表达式:

//*:Reply[*:Name="Name of Reply"]/*:ID

预期的返回结果是:

回复 1 的 ID

和:

//*:Reply[*:Name="Name of Reply"]/*:ContentsofReply/*:Content/*:IDofContent

预期的返回结果是:

内容 1 的 ID

如何使用 lxml 库在 Python 3 中获得相同的结果?提前致谢。

解决方法

您问题中的 xpath 表达式包含 *: 前缀,旨在用于不在您的示例 xml 中的命名空间。

要使用 lxml 从示例 xml 中提取相同的数据,请将表达式更改为

//Reply[Name="Name of Reply"]/ContentsofReply/Content/IDofContent/text()

得到

['ID of Content 1']

//Reply[Name="Name of Reply"]/ID/text()

得到

['ID of Reply 1']