我已经提供了一个 .NET 答案,但这里是如何使用 XSLT 完成的:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:variable name="space" select="' '" />
<xsl:variable name="spaceLen" select="string-length($space)" />
<xsl:template match="text()" />
<xsl:template match="*/*">
<xsl:param name="parentLeading" select="0" />
<xsl:variable name="leadingText">
<xsl:apply-templates select="preceding-sibling::node()" mode="value" />
</xsl:variable>
<xsl:variable name="leading" select="$parentLeading +
string-length($leadingText)" />
<xsl:variable name="nameAndRange"
select="concat(local-name(), ' ', $leading,
'-', $leading + string-length())" />
<xsl:variable name="spacing"
select="substring($space, 1, 14 - string-length($nameAndRange))" />
<xsl:value-of select="concat($nameAndRange, $spacing,
'# "', ., '"
')"/>
<xsl:apply-templates>
<xsl:with-param name="parentLeading" select="$leading" />
</xsl:apply-templates>
</xsl:template>
<xsl:template match="node()" mode="value">
<xsl:value-of select="." />
</xsl:template>
</xsl:stylesheet>
在此输入上运行时:
<n>the <PET>calico</PET> cat and the <PET>black do</PET>g</n>
结果是:
PET 4-10 # "calico"
PET 23-31 # "black do"
在此输入上运行时:
<n>the <PET><COLOR>calico</COLOR></PET> cat and the <PET><COLOR>bla</COLOR>ck do</PET>g</n>
结果是:
PET 4-10 # "calico"
COLOR 4-10 # "calico"
PET 23-31 # "black do"
COLOR 23-26 # "bla"