关于 URL 转换(以及使用的 XML 工具)的问题非常非正式,但我们假设 3xx 对原始 URL 的响应以及输出结果 URL 的意图。例如:
$ curl --silent --head http://stackoverflow.com | grep Location
Location: https://stackoverflow.com/
要在转换 XML 时做同样的事情,XSLT 处理器需要一个 HTTP 客户端。 EXPath 中有HTTP Client module,它是XPath 扩展规范和实现的集合。
要快速安装 EXPath,download page 上提供了安装程序。它带有 Saxon XSLT 处理器。在撰写本文时,它指的是expath-repo-installer-0.13.1.jar。像这样运行它:
java -jar expath-repo-installer-0.13.1.jar
安装后,下载 Saxon 的 HTTP 客户端模块 expath-http-client-saxon-0.12.0.zip 并从中提取 expath-http-client-saxon-0.12.0.xar。然后将其安装到 EXPath 存储库:
mkdir repo
bin/xrepo --repo repo install /path/to/expath-http-client-saxon-0.12.0.xar
那么你可以使用bin/saxon。
data.xml
<?xml version="1.0" encoding="utf-8"?>
<data>
<datum><url>http://python.org</url></datum>
<datum><url>http://stackoverflow.com</url></datum>
</data>
text.xslt
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:http="http://expath.org/ns/http-client"
exclude-result-prefixes="#all"
version="2.0">
<xsl:import href="http://expath.org/ns/http-client.xsl"/>
<xsl:output method="xml" encoding="utf-8" indent="yes"/>
<xsl:template match="/">
<result>
<xsl:for-each select="data/datum">
<!-- the request element -->
<xsl:variable name="request" as="element(http:request)">
<http:request method="head" follow-redirect="false">
<xsl:attribute name="href">
<xsl:value-of select="url"/>
</xsl:attribute>
</http:request>
</xsl:variable>
<!-- sending the request -->
<xsl:variable name="response" select="http:send-request($request)"/>
<!-- output -->
<url>
<orig><xsl:value-of select="url"/></orig>
<location>
<xsl:value-of
select="$response[1]/header[@name='location']/@value"/>
</location>
</url>
</xsl:for-each>
</result>
</xsl:template>
</xsl:stylesheet>
有关如何控制 HTTP 客户端的更多详细信息,请参阅the module's spec。
然后bin/saxon --repo repo data.xml test.xslt 产生:
<?xml version="1.0" encoding="utf-8"?>
<result>
<url>
<orig>http://python.org</orig>
<location>https://python.org/</location>
</url>
<url>
<orig>http://stackoverflow.com</orig>
<location>https://stackoverflow.com/</location>
</url>
</result>