by use XSLT, I want to create a tag named "g" as an inline element. but always got a block element.
<xsl:element name="g">
<xsl:text>asdf</xsl:text>
</xsl:element>
got this:
some text
<g>asdf</g>some text
If changed tag name as "span", will get something like this:
some text<span>asdf</span>some text
here is a reproducible example:
the xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:n="http://www.tei-c.org/ns/1.0"
exclude-result-prefixes="n"
>
<xsl:output encoding="UTF-8" method="html"/>
<xsl:template match="/n:TEI/n:text/n:body">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="n:g">
<xsl:element name="g">
<xsl:attribute name="type">
<xsl:text>gaiji</xsl:text>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
<xsl:element name="span">
<xsl:attribute name="class">
<xsl:text>gaiji</xsl:text>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
</xsl:stylesheet>
the xml:
<?xml version="1.0" encoding="UTF-8"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0">
<text>
<body>
some text<g>char</g>some text
</body>
</text>
</TEI>
the output( by saxonb-xslt,Saxon 9.1.0.8J ):
<html>
<body>some text
<g type="gaiji">char</g><span class="gaiji">char</span>some text
</body>
</html>
The difference is that the previous case (tag "g") will generate some useless spaces. (around the new tag) and will eventually display on the web page.
Is there any way to generate tag "g" as inline element like "span"?
I’ve tried searching the web and haven’t seen a similar problem.
2
Answers
The difference is in the way the result is being serialized. The serializer knows that
span
is an inline element, so it suppresses addition of whitespace.This suggests that you are using the HTML serialization method to serialize something that isn’t actually HTML. Perhaps you need to switch to the XML serialization method. Check your xsl:output declarations.
Also, with XSLT questions you should always tag the question with a specific XSLT version, since they are very different.
The whitespace you see before the
g
element is a result of indentation performed by the serializer.You can eliminate all such whitespace globally by adding
indent="no"
to thexsl:output
declaration, or by changing the output method toxml
(which makesno
the default value for theindent
attribute). I don’t know of a method to turn it off locally for some elements only.However, you can improve the result’s readability by passing some of your own whitespace from the stylesheet to the output. Here is an example (which also simplifies your existing code):
XSLT 2.0
Result