Ruby Regexp 提取 XML 字符串中的特定元素 [英] Ruby Regexp to extract specific elements in an XML string

查看:26
本文介绍了Ruby Regexp 提取 XML 字符串中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 XML 字符串,它或多或少总是相同的.我宁愿避免对这么一小段代码使用 XML 解析器,但我认为 Regexp 会有所帮助.

I have a simple XML string, that is more or less always the same. I'd rather avoid using an XML parser for such a little piece of code, and I though Regexp would help.

XML 字符串如下所示:

The XML string looks like :

<?xml version="1.0"?>
<methodCall>
  <methodName>weblogUpdates.extendedPing</methodName>
  <params>
    <param>
      <value>Official Google Blog</value>
    </param>
    <param>
      <value>http://googleblog.blogspot.com/</value>
    </param>
    <param>
      <value>http://googleblog.blogspot.com/</value>
    </param>
    <param>
      <value>http://googleblog.blogspot.com/atom.xml</value>
    </param>
  </params>
</methodCall>

我想提取每个参数的值(并保持顺序).

I want to extract the values of each param (and maintain the order).

我想出了 /<value>(.*)<\/value>/xi 但这只是匹配第一个值:/

I came up with /<value>(.*)<\/value>/xi but that just macthes the very first value :/

推荐答案

使用 Ruby 解析 XML 是微不足道的,请不要尝试使用正则表达式解析 XML - 这是出了名的困难且容易出错.

Parsing XML with Ruby is trivial, please don't try to parse XML with a regular expression - it is notoriously difficult and error-prone.

虽然尝试使用正则表达式可能很诱人,但请不要这样做.无论您如何用螺丝刀敲碎钉子,它都无法用作锤子 - 请使用您可以使用的众多精美锤子之一.

While it may be tempting to try and use a regular expression, please don't. No matter how hard you try to smash that nail with the screwdriver it won't work as a hammer - please use one of the many wonderful hammers at your disposal.

这篇关于Ruby Regexp 提取 XML 字符串中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆