我想删除 Space 并仅在元素之间返回特定子元素(即)的“数学”,如下面的 XML 所述。我试过 <xsl:strip-space elements="m:math"/>
.但它删除了所有元素的空间。我需要保留 <style>
之后的空间<b>
之前的元素和空格元素。
输入 XML:
<?xml version="1.0"?>
<chapter xmlns="http://www.w3.org/1998/Math/MathML">
<style>This is style</style>
<math display="block">
<munder>
<mi mathvariant="normal">BASE</mi>
<mi mathvariant="normal">under</mi>
</munder>
<mo>=</mo>
<munder>
<mrow>
<munder>
<mi mathvariant="normal">BASE</mi>
<mi mathvariant="normal">under</mi>
</munder>
</mrow>
<mphantom>
<mi mathvariant="normal">under</mi>
</mphantom>
</munder>
</math>
<b>This is bold</b>
</chapter>
XSLT 尝试过:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:m="http://www.w3.org/1998/Math/MathML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML">
<xsl:output method="xml" encoding="UTF-8" indent="no"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
要求的输出:
<?xml version='1.0' encoding='UTF-8'?>
<chapter xmlns="http://www.w3.org/1998/Math/MathML"><style>This is style</style> <math display="block"><munder><mi mathvariant="normal">BASE</mi><mi mathvariant="normal">under</mi></munder><mo>=</mo><munder><mrow><munder><mi mathvariant="normal">BASE</mi><mi mathvariant="normal">under</mi></munder></mrow><mphantom><mi mathvariant="normal">under</mi></mphantom></munder></math> <b>This is bold</b></chapter>
最佳答案
编辑:虽然这个答案对于这个问题无效,但我保留它以供引用,因为我已经在 linearize XML
代码中解释了每个模板的重要性。并将相关答案作为新答案发布回答..
你不需要 strip-space,这应该可以..
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="no" omit-xml-declaration="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space()" />
</xsl:template>
</xsl:stylesheet>
解释:
<xsl:output indent="no" omit-xml-declaration="yes"/>
indent = 'no' 负责删除两个节点之间的附加空间。omit-xml-declaration
从输出 XML 中删除 xml 声明。这在您的情况下是可选的..
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
按原样复制节点..除了没有缩进..
<xsl:template match="text()">
<xsl:value-of select="normalize-space()" />
</xsl:template>
将不需要的空白字符转换为单空格字符 .. 示例:
<node>
there is lots of space
</node>
输出将是这样的:
<node>there is lots of space</node>
关于xslt - 使用 XSLT 删除不需要的空格并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16052410/