【问题标题】:Parse XML with lxml and Python [duplicate]使用 lxml 和 Python 解析 XML [重复]
【发布时间】:2013-06-28 22:15:43
【问题描述】:

我有下面的 XML:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <LogonResponse xmlns="http://schemas.navitaire.com/ClientServices/Common/SessionManagerClient">
      <LogonResult>
        <LastName xmlns="http://schemas.navitaire.com/Messages/Session/Response">Mont</LastName>
        <FirstName xmlns="http://schemas.navitaire.com/Messages/Session/Response">Paul</FirstName>
        <PersonID xmlns="http://schemas.navitaire.com/Messages/Session/Response">123</PersonID>
        <CultureCode xmlns="http://schemas.navitaire.com/Messages/Session/Response">en-US</CultureCode>
        <CurrencyCode xmlns="http://schemas.navitaire.com/Messages/Session/Response">Dollar</CurrencyCode>
        <LastLogon xmlns="http://schemas.navitaire.com/Messages/Session/Response">0001-01-01T00:00:00</LastLogon>
        <SessionContext xmlns="http://schemas.navitaire.com/Common">
          <SessionControl>OneOnly</SessionControl>
          <SystemType>Default</SystemType>
          <SessionID>0</SessionID>
          <SequenceNumber>0</SequenceNumber>
          <MessageVersion>0</MessageVersion>
          <Signature>00000000-0000-0000-0000-000000000000</Signature>
          <ChannelType>Default</ChannelType>
          <InTransaction>false</InTransaction>
          <TransactionDepth>0</TransactionDepth>
          <TransactionCount>0</TransactionCount>
          <SecureToken>kFBOdZGqP6s=|/TftALE31236mSppQoFpArBizzz=</SecureToken>
        </SessionContext>
      </LogonResult>
    </LogonResponse>
  </s:Body>
</s:Envelope>

想法是将 SecureToken、Signature 和 MessageVersion 抓取到变量中,我正在尝试使用以下代码:

SecureToken = tree.find('.//SecureToken').text

但运气不好,我需要使用所有命名空间或其他东西来实现这一点?

请记住,此 XML 是来自请求的返回,我无法对其进行编辑。

【问题讨论】:

标签: python xml parsing lxml


【解决方案1】:

如果您想避免完全处理命名空间,您可以执行类似的操作

tree.xpath("//*[local-name() = 'SecureToken']")[0].text

这将解决这个特殊问题,但有其自身的局限性,在大多数情况下,我宁愿进行更详细的命名空间感知搜索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    相关资源
    最近更新 更多