1

我有这种 XML 结构,我需要打印出两个段落部分包含的内容。怎么做?基本上我想到了 for-each 循环,但是在 xsl:value-of 构造里面放什么?谢谢!

   <slideshow>
        <slide id="A1">
            <title>XML techniques</title>
            <paragraph> Slideshow prepresents different kind of <bold>XML</bold> techniques </paragraph>
            <paragraph> Most common XML Techniques are </paragraph>
4

2 回答 2

2

假设您的 XSLT 看起来像

<xsl:for-each select="//paragraph">
  ???
</xsl:for-each>

你可以写:

<xsl:for-each select="//paragraph">
  <xsl:copy-of select="node()"/>
</xsl:for-each>

...这将返回节点的副本——文本和元素——它们是段落的子节点。

根据您拥有并想要执行的其他规则,您还可以编写:

<xsl:for-each select="//paragraph">
  <xsl:apply-templates select="node()"/>
</xsl:for-each>

...这也将返回节点的副本 - 文本和元素 - 作为段落的子节点,除非您有其他模板覆盖该行为。

如果您想要的只是每个段落中的原始文本(即没有粗体标签),您可以使用value-of.

<xsl:for-each select="//paragraph">
  <xsl:value-of select="."/>
</xsl:for-each>

如果这就是你所做的一切,你甚至可以把它写成:

<xsl:value-of select="//paragraph"/>

(注意:我以 //paragraph 为例,因为没有提供上下文,但您可能希望浏览幻灯片并选择段落子项)。

于 2015-09-25T16:59:19.040 回答
2

你写了:

基本上我想到了 for-each 循环,

在处理节点时,xsl:for-each很少需要 a。使用xsl:apply-templates选择所需的节点。如果没有匹配的模板,这将默认输出节点(文本)的值:

<xsl:template match="slide">
    <!-- just process selection of children -->
    <xsl:apply-templates select="paragraph" />
</xsl:template>

<!-- add this in case you already have an identity template -->
<xsl:template match="paragraph">
    <!-- select only the immediate text children (without <b> for instance) -->
    <xsl:value-of select="text()" />
    <!-- OR: select the value, incl. all children (using "node()" is equiv.) -->
    <xsl:value-of select="." />
</xsl:template>

你写道:

但是在 xsl:value-of 构造里面放什么?谢谢!

这很大程度上取决于焦点。焦点通常由第一个祖先指令xsl:templatexsl:for-each. 假设您的焦点是<slideshow>,表达式将是:

<xsl:value-of select="slide/paragraph" />

如果焦点已经在 上paragraph,您可以使用select="text()"(选择所有文本子节点,但不更深),或select="."(选择当前节点,也获取子节点的值)。

但请参阅上文以了解更具弹性的方法。使用应用模板可以更轻松地为更改和可维护性编写代码。

于 2015-09-26T15:16:48.920 回答