I'm creating html with PHP (simpleXML), a XML-document and XSL.
Is there a way to replace all elements with a specific name (ie. ) with a html-tag (ie. ). I guess the answer is 'yes", but how do I do it?
With my code, the keyword-element must be the top child of the root-element for it to work.
The following don't work:
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>
The <keyword>
-element can exist on all kinds of levels in the document, lets say even in the title. How can I then select it from the XSL? I guess there is something to do with the 'match'-attribute. I tried match="*/keyword" without any luck.
This code works when the <keyword>
-element is the top child of the root, but won't work inside for example the <text>
-element.
I have modified your input example to:
<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>
Using the following stylesheet:
<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>
you will get the following output:
<?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>
I'm not total sure what you are trying to do, but the following query:
<xsl:value-of select="//keyword/text()"/>
will select all <keyword>
element's content regardless of their position in tree. This because I'm using the //
in front of
I think what you are looking for is on this question .
Basically, the */keyword
is looking for a string that has "/keyword" in it, and not the actual node.
If you try
<xsl:template match="*[starts-with(name(), 'keyword')]">
You should be in good shape.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.