首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用第一正则表达式的输出编写第二正则表达式,并用第二正则表达式的祖先覆盖子字符串

问使用第一正则表达式的输出编写第二正则表达式,并用第二正则表达式的祖先覆盖子字符串
EN

Stack Overflow用户
提问于 2015-04-17 17:02:15
回答 1查看 38关注 0票数 0

我有这样的XML:

代码语言:javascript
复制
<c hw="A">
  <e hw="aardvark">
    <d t="see &lt;a onclick=&quot;goToEntryWithId('2319')&quot;&gt;mammals&lt;/a&gt; for more details."/>
  </e>
</c>

在XML中使用,elswhere:

代码语言:javascript
复制
<c hw="M">
  <e hw="mammals" i="2319">
    <d t="Here's useful info about mammals."/>
  </e>
</c>

我根据标记将XML分解为多个HTML文件,我希望将onclick更改为具有适当目标的href。

期望产出:

代码语言:javascript
复制
<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('####')事件执行此操作,包括对同一行中的多次命中。

我有什么办法做到这一点吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-18 09:07:02

您还没有说明要使用哪个版本的XSLT和哪个XSLT处理器,但假设您可以使用Saxon9.6HE,那么至少可以使用XPath 3.0 parse-xml-fragment函数将编码的标记解析为节点,然后进一步处理它们,只需要正则表达式来查找和提取onclick属性。

基于此,我创建了一个示例输入

代码语言:javascript
复制
<root>
  <references>
    <c hw="A">
      <e hw="aardvark">
        <d t="see &lt;a onclick=&quot;goToEntryWithId('2319')&quot;&gt;mammals&lt;/a&gt; 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>

和一个样式表

代码语言:javascript
复制
<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)创建输出

代码语言:javascript
复制
<html>
   <body>
      <p>see <a href="M.html#2319">mammals</a> for more details.
      </p>
   </body>
</html>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29705339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档