gpt4 book ai didi

xml - XSLT 混合内容节点

转载 作者:数据小太阳 更新时间:2023-10-29 01:41:44 24 4
gpt4 key购买 nike

我有一个很愚蠢的问题。如何确保我的 XML 混合内容节点不会混淆?比方说,我有一个类似于此的 XML 结构。

<root>
<book>
<title>Stuff</title>
<description> This book is <i>great</i> if you need to know about stuff.
I suggest <link ref="Things">this one</link> if you need to know
about things. </description>
</book>
[other books]
</root>

我需要最终的内容看起来像这样

<h1>List of books</h1>
<h2><a name="Stuff"/>Stuff</h2>
<p> This book is <i>great</i> if you need to know about stuff.
I suggest <a href="#Things">this one</a> if you need to know
about things. </p>

但我无法提取文本节点的部分,我总是抓取整个内容。我正在使用后代 Axis 。知道我做错了什么吗?

这是我的 xslt:

<xsl:template match="description/*">
<xsl:for-each select="following-sibling::*">
<xsl:choose>
<xsl:when test="name(.)='link'">
<a href="{@ref}"><xsl:value-of select="."/></a>
</xsl:when>
<xsl:when test="name(.)='em'">
<em><xsl:value-of select="."/></em>
</xsl:when>
<xsl:otherwise><p><xsl:value-of select="."/></p></xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>

请注意,随附的 XML 和生成的 html 仅仅是示例,为了清楚起见,我必须处理一个更大的结构,我没有将其包含在其中。

最佳答案

<xsl:apply-templates>是你的 friend :

<xsl:stylesheet 
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:output method="html" />

<xsl:template match="root">
<h1>List of books</h1>
<xsl:apply-templates />
</xsl:template>

<!-- a <book> consists of its <title> and <description> -->
<xsl:template match="book">
<xsl:apply-templates select="title" />
<xsl:apply-templates select="description" />
</xsl:template>

<!-- <title> is turned into a <h2> -->
<xsl:template match="title">
<h2>
<a name="{.}"/>
<xsl:value-of select="." />
</h2>
</xsl:template>

<!-- <description> is turned into a <p> -->
<xsl:template match="description">
<p>
<xsl:apply-templates />
</p>
</xsl:template>

<!-- default rule: copy any node beneath <description> -->
<xsl:template match="description//*">
<xsl:copy>
<xsl:copy-of select="@*" />
<xsl:apply-templates />
</xsl:copy>
</xsl:template>

<!-- override rule: <link> nodes get special treatment -->
<xsl:template match="description//link">
<a href="#{@ref}">
<xsl:apply-templates />
</a>
</xsl:template>

<!-- default rule: ignore any unspecific text node -->
<xsl:template match="text()" />

<!-- override rule: copy any text node beneath description -->
<xsl:template match="description//text()">
<xsl:copy-of select="." />
</xsl:template>

</xsl:stylesheet>

为您的输入 XML 生成以下输出(注意:为了可读性,我通过 tidy 对其进行了管道传输。在此过程中删除了不相关的空白):

<h1>List of books</h1>
<h2><a name="Stuff">Stuff</h2>
<p>This book is <i>great</i> if you need to know about stuff. I
suggest <a href="#Things">this one</a> if you need to know about
things.</p>

关于xml - XSLT 混合内容节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1525285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com