我有这样的XML:
<c hw="A">
<e hw="aardvark">
<d t="see <a onclick="goToEntryWithId('2319')">mammals</a> for more details."/>
</e>
</c>在XML中使用,elswhere:
<c hw="M">
<e hw="mammals" i="2319">
<d t="Here's useful info about mammals."/>
</e>
</c>我根据标记将XML分解为多个HTML文件,我希望将onclick更改为具有适当目标的href。
期望产出:
<p>See <a href="M.html#2319">mammals</a> for more details.我需要用某种方式
1)查找包含####的onclick表达式的匹配项,
2)取该onclick中引用的数字(####),并在XML文档的其他地方找到它,其中它隐藏在类似<e i="####">的某个地方。
3)查找搜索结果的祖先::C@hw父级
4)用简单的href="[filename].html#[####]"替换onclick表达式
5)对XML中的每个onclick="goToEntryWithId('####')事件执行此操作,包括对同一行中的多次命中。
我有什么办法做到这一点吗?
发布于 2015-04-18 09:07:02
您还没有说明要使用哪个版本的XSLT和哪个XSLT处理器,但假设您可以使用Saxon9.6HE,那么至少可以使用XPath 3.0 parse-xml-fragment函数将编码的标记解析为节点,然后进一步处理它们,只需要正则表达式来查找和提取onclick属性。
基于此,我创建了一个示例输入
<root>
<references>
<c hw="A">
<e hw="aardvark">
<d t="see <a onclick="goToEntryWithId('2319')">mammals</a> for more details."/>
</e>
</c>
</references>
<content>
<c hw="M">
<e hw="mammals" i="2319">
<d t="Here's useful info about mammals."/>
</e>
</c>
</content>
</root>和一个样式表
<xsl:stylesheet
version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs">
<xsl:param name="pattern" as="xs:string">^goToEntryWithId\('[0-9]+'\)$</xsl:param>
<xsl:output method="html" indent="yes"/>
<xsl:key name="id" match="content/c/e" use="@i"/>
<xsl:variable name="main-doc" select="/"/>
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates select="root/references//@t"/>
</body>
</html>
</xsl:template>
<xsl:template match="references/c/e/d/@t">
<p>
<xsl:apply-templates select="parse-xml-fragment(.)/node()"/>
</p>
</xsl:template>
<xsl:template match="a[@onclick[matches(., $pattern)]]">
<xsl:variable name="id" select="replace(@onclick, '[^0-9]+', '')"/>
<xsl:variable name="referenced-c" select="key('id', $id, $main-doc)/ancestor::c[@hw]"/>
<a href="{$referenced-c/@hw}.html#{$id}">
<xsl:apply-templates/>
</a>
</xsl:template>
</xsl:stylesheet>使用Saxon9.6HE或Saxon9.5EE(参见http://xsltransform.net/94hvTzw)创建输出
<html>
<body>
<p>see <a href="M.html#2319">mammals</a> for more details.
</p>
</body>
</html>https://stackoverflow.com/questions/29705339
复制相似问题