获取具有独立于元素级别的特定名称的所有标记

时间:2013-12-12 15:59:22

标签: php xml xslt

我正在使用PHP(simpleXML),XML文档和XSL创建html。

有没有办法用html-tag(即。)替换具有特定名称(即。)的所有元素。我猜答案是'是',但我该怎么做?

使用我的代码,keyword-element必须是root元素的顶级子元素才能工作。

以下不起作用:

XML:

<document>
<chapter>This is the first chapter</chapter>
<text>This is a text, with a <keyword>keyword</keyword></text>
</document>

XSL:

    <xsl:template match="text">
            <xsl:value-of select="."/>
    </xsl:template>
<xsl:template match="*[starts-with(name(), 'keyword')]">
            <xsl:copy>
                <b>
                    <xsl:value-of select="."/>
                </b>
            </xsl:copy>
    </xsl:template>

<keyword> - 元素可以存在于文档中的各种级别上,即使在标题中也是如此。我怎样才能从XSL中选择它?我想与'match'属性有关。我没有运气就试过match =“* / keyword”。

<keyword> - 元素是根的顶级子元素时,此代码有效,但不会在内部工作,例如<text> - 元素。

3 个答案:

答案 0 :(得分:2)

我已将您的输入示例修改为:

<document>
    <title>This is the <keyword>first</keyword> title</title>
    <chapter>This is the <keyword>second</keyword> chapter</chapter>
    <text>This is a text, with a <keyword>third</keyword> keyword in it.</text>
</document>

使用以下样式表:

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

<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<!-- Identity Transform -->
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

<!-- exception -->
<xsl:template match="keyword">
    <b><xsl:apply-templates/></b>
</xsl:template>

</xsl:stylesheet> 

您将获得以下输出:

<?xml version="1.0" encoding="utf-8"?>
<document>
    <title>This is the <b>first</b> title</title>
    <chapter>This is the <b>second</b> chapter</chapter>
    <text>This is a text, with a <b>third</b> keyword in it.</text>
</document>

答案 1 :(得分:1)

我不完全确定你要做什么,但以下查询:

 <xsl:value-of select="//keyword/text()"/>

将选择所有<keyword>元素的内容,无论它们在树中的位置如何。这是因为我在

前面使用了//

答案 2 :(得分:1)

我认为你要找的是this question

基本上,*/keyword正在查找其中包含“/ keyword”的字符串,而不是实际节点。

如果您尝试

    <xsl:template match="*[starts-with(name(), 'keyword')]">

你应该保持良好状态。