【问题标题】:Parsing XML Recieved from Curl for Specific Values解析从 Curl 接收的 XML 以获取特定值
【发布时间】:2012-11-11 16:41:05
【问题描述】:

我正在尝试为<cookie></cookie> 之间的数据以及account-id="" 之间的数据(尾引号)过滤此代码

<?xml version="1.0" encoding="utf-8"?>
<results>
 <status code="ok"/>
 <common locale="en" time-zone-id="85">
  <cookie>na3breezfxm5hk6co2kfzuxq</cookie>
  <date>2012-11-11T16:26:52.713+00:00</date>
  <host>http://meet97263421.adobeconnect.com</host>
  <local-host>pacna3app09</local-host>
  <admin-host>na3cps.adobeconnect.com</admin-host>
  <url>/api/xml?action=common-info</url>
  <version>8.2.2.0</version>
  <tos-version>7.5</tos-version>
  <product-notification>true</product-notification>
  <account account-id="1013353222"/>
  <user-agent>curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5</user-agent>
 </common>
</results>

任何帮助将不胜感激。

编辑

这是我运行返回上述 xml 的 curl 命令。

curl -s http://meet97263421.adobeconnect.com/api/xml?action=common-info

【问题讨论】:

    标签: xml curl xml-parsing


    【解决方案1】:

    一般来说,正则表达式(因此是 greparen't well-suited to parsing XML,但如果您能保证输入格式正确且一致,您可以使用 grep 的 perl 样式正则表达式(在系统上谁的 grep 有它们):

    grep -oP '(?<=<cookie>).*?(?=</cookie>)'
    grep -oP '(?<=account-id=").*?(?=")'
    

    如果你想让它们在同一个命令中,你可以用|分隔它们,但是你必须告诉哪个匹配哪个。

    grep -oP '(?<=<cookie>).*?(?=</cookie>)|(?<=account-id=").*?(?=")'
    

    【讨论】:

    • 您的grep 命令效果很好!我将如何使用 -e 命令。我已经用我的curl 输入编辑了这个问题。
    • 上面写着grep: the -P option only supports a single pattern
    • 有趣。您可以使用替代 (|),我已经测试过这个。
    【解决方案2】:

    正如@Kevin 所说,正则表达式不适合解析 XML。

    更好的方法是使用 xmllint 程序,该程序应用 xpath 表达式,如下所示:

    $ xmllint --xpath "string(/results/common/cookie)" data.xml
    na3breezfxm5hk6co2kfzuxq
    
    $ xmllint --xpath "string(/results/common/account/@account-id)" data.xml
    1013353222
    

    【讨论】:

      【解决方案3】:

      使用这些 XPath 表达式

      /results/common/cookie
      
      /results/common/account/@account-id
      

      使用命令行 XPath 解释器

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-05
        • 2012-08-22
        • 2015-11-27
        • 2018-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多