XSLT从xml文件中的所有URL中删除查询字符串

时间:2011-05-26 16:44:36

标签: xml regex xslt replace

我需要从MRSS RSS提要中的所有属性执行正则表达式样式替换查询字符串,将它们剥离到仅仅是网址。我在这里尝试了一些使用建议的东西:XSLT Replace function not found但无济于事

<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
<channel>
<atom:link href="http://www.videojug.com/user/metacafefamilyandeducation/subscriptions.mrss" type="application/rss+xml" rel="self" />
<title>How to and instructional videos from Videojug.com</title>
<description>Award-winning Videojug.com has over 50k professionally-made instructional videos.</description>
<link>http://www.videojug.com</link>
<item>
  <title>How To Calculate Median</title>
  <media:content url="http://direct.someurl.com/54/543178dd-11a7-4b8d-764c-ff0008cd2e95/how-to-calculate-median__VJ480PENG.mp4?somequerystring" type="video/mp4" bitrate="1200" height="848" duration="169" width="480">
    <media:title>How To Calculate Median</media:title>
    ..
  </media:content>
</item>

任何建议都非常有用

2 个答案:

答案 0 :(得分:3)

如果您使用的是XSLT 2.0,则可以使用tokenize()

  <xsl:template match="media:content">
    <xsl:value-of select="tokenize(@url,'\?')[1]"/>
  </xsl:template>

以下是仅更改url的{​​{1}}属性的另一个示例:

media:content

修改

要处理实例中的所有 <xsl:template match="media:content"> <media:content url="{tokenize(@url,'\?')[1]}"> <xsl:copy-of select="@*[not(name()='url')]"/> <xsl:apply-templates/> </media:content> </xsl:template> 属性,并保持其他所有属性不变,请使用标识转换,并仅使用url的模板覆盖它。

以下是示例XML的修改版本。我已经为@url添加了两个属性进行测试。 <{1}}属性应保持不变,并且应处理description属性。

<强> XML

attr

<强> XSLT

url

输出(使用Saxon 9.3.0.5)

<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
  <channel>
    <atom:link href="http://www.videojug.com/user/metacafefamilyandeducation/subscriptions.mrss" type="application/rss+xml" rel="self"/>
    <title>How to and instructional videos from Videojug.com</title>
    <!-- added some attributes for testing -->
    <description attr="don't delete me!" url="http://www.test.com/foo?anotherquerystring">Award-winning Videojug.com has over 50k professionally-made instructional videos.</description>
    <link>http://www.videojug.com</link>
    <item>
      <title>How To Calculate Median</title>
      <media:content url="http://direct.someurl.com/54/543178dd-11a7-4b8d-764c-ff0008cd2e95/how-to-calculate-median__VJ480PENG.mp4?somequerystring" type="video/mp4" bitrate="1200" height="848"
        duration="169" width="480">
        <media:title>How To Calculate Median</media:title>
        .. 
      </media:content>
    </item>
  </channel>
</rss>

答案 1 :(得分:2)

使用XSLT 2.0,XSLT中的字符串处理通常要容易得多,但在这种情况下,使用自XSLT 1.0以来存在的substring-before()函数可以很容易地实现要求。