[英]I want to parse text from a compressed XML feed using awk
我試圖從http://rss.slashdot.org/Slashdot/slashdot的壓縮XML提要中解析<title>
和<description>
。 我正在嘗試執行以下操作
curl --silent "http://rss.slashdot.org/Slashdot/slashdot" | awk '/\btitle\b(.*?)\bdescription\b/'
和grep -E
等,但是我無法獲得想要的子字符串。 它總是在壓縮后返回整個XML,並且數據在一行中。
我可以通過在文本編輯器中運行它來測試我的Regex字符串。
感謝您的幫助!! 謝謝!
使用XML解析器會有所幫助,這里使用perl
和XML::Twig
進行測試。 使其適應您的需求。
script.pl
內容:
#!/usr/bin/env perl
use warnings;
use strict;
use XML::Twig;
my $twig = XML::Twig->new(
twig_handlers => {
'title' => \&extract_text,
'description' => \&extract_text,
},
)->parsefile( shift );
sub extract_text {
my ($t, $e) = @_;
printf qq|%s\n=================\n|, $e->tag;
printf qq|%s\n\n|, $e->text;
}
像這樣運行:
curl --silent "http://rss.slashdot.org/Slashdot/slashdot" | perl script.pl -
對於每對標題和描述,這類似於以下內容:
title
=================
Proof-of-Concept Port of XBMC to SDL 2.0 and Wayland
description
=================
hypnosec wrote in with news that XBMC has ...
這是XSLT解決方案:
curl -s -o- http://rss.slashdot.org/Slashdot/slashdot | xsltproc slashdot.xsl -
slashdot.xsl
在哪里
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:variable name="newline">
<xsl:text>
</xsl:text>
</xsl:variable>
<xsl:template match="/">
<xsl:apply-templates select='//item' />
</xsl:template>
<xsl:template match='//item'>
<xsl:value-of select='title' /><xsl:value-of select='$newline' />
<xsl:text>====</xsl:text><xsl:value-of select='$newline' />
<xsl:value-of select='description' /><xsl:value-of select='$newline' />
<xsl:value-of select='$newline' />
</xsl:template>
</xsl:stylesheet>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.