【问题标题】:Java - Get src value from xmlJava - 从 xml 获取 src 值
【发布时间】:2014-08-05 22:20:11
【问题描述】:

我有一个来自 xml 节点的字符串:

<p>
  <a href="http://www.windoctor.it/hardware/amd-serie-a10-7850k-3-7-ghz-4-core/">
    <img align="left" hspace="5" width="100" src="http://www.windoctor.it/wp-content/uploads/2014/02/g_21948019_001.jpg" class="alignleft wp-post-image tfe" alt="g_21948019_001" title="" />
  </a>
  Processori AMD A-Series APU l&#8217;APU più avanzata di AMD, l&#8217;AMD A10-7850K. Talmente rivoluzionaria da sfidare la definizione stessa di processore. Con 12 core di elaborazione (4 CPU + 8 GPU)3 con la scheda grafica AMD Radeon™ R7 e funzioni esclusive come la tecnologia AMD TrueAudio4 per un audio coinvolgente, è in grado di gestire Battlefield 4™ o qualsiasi altra cosa desideri. I processori AMD A10 ti permettono di: Liberare tutto… 
  <span class="read-more">
    <a href="http://www.windoctor.it/hardware/amd-serie-a10-7850k-3-7-ghz-4-core/">
      Read More &#187;
    </a>
  </span>
</p>

<p>
  The post 
  <a rel="nofollow" href="http://www.windoctor.it/hardware/amd-serie-a10-7850k-3-7-ghz-4-core/">
    AMD SERIE A10-7850K
  </a>
  appeared first on 
  <a rel="nofollow" href="http://www.windoctor.it">
    Win Doctor
  </a>
  .
</p>

我想在图像标签的 src 属性中获取值。在 C# 中,我在正则表达式函数中使用了"&lt;img.+?src=[\"'](.+?)[\"'].+?&gt;",但在 java 中它不起作用。

提前致谢:)

【问题讨论】:

  • 为什么不使用解析器?
  • 不要使用正则表达式来解析非常规字符串。使用真正的 XML 解析器。
  • 使用适当的解析器和 xPath
  • 我是唯一一个在那里看到 html 而不是 XML 的人吗?
  • @m0s:不,我现在也看到了……使用 JSoup 或其他一些 HTML 解析器。

标签: java regex eclipse


【解决方案1】:

你可以这样做

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;

public class Image{

    public static void main(String[] args) throws Exception {
        String s = FileUtils.readFileToString(new File(
                "E:\\workspace\\XYZ\\src\\xpath.txt"));

        Pattern p = Pattern.compile(
                "(.*?)(<img)(.*?)(src=\")(.*?)(\")(.*?)(\\/>)(.*?)",
                //                       ^^^^^
                // 1     2    3     4      5   6    7    8     9
                Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher m = p.matcher(s);
        while (m.find()) { //use while to find all images, and if for only the first one
            System.out.print(m.group(5));
        }
    }
}

ps。 http://txt2re.com 有很大帮助。

【讨论】:

    【解决方案2】:

    您需要转义反斜杠。

    但更好的方法是使用 XPath。

    【讨论】:

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