Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

xml - Removing Attributes from XSLT and working with result set

Is it possible to remove xml attributes from XSLT AND work with the resulting transform?

In other words, I have the following XML:

<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/xsl" href="XML_TEST.xslt"?>
<report xmlns="abc123">
<book>
<page id="22">

</page>
<page id="23">

</page>
</book>
</report>

I know that I can use the following XSLT to strip the attributes:

 <xsl:template match ="@*" >
            <xsl:attribute name ="{local-name()}" >
                <xsl:value-of select ="." />
            </xsl:attribute>
            <xsl:apply-templates/>
        </xsl:template>
        <xsl:template match ="*" >
            <xsl:element name ="{local-name()}" >
                <xsl:apply-templates select ="@* | node()" />
            </xsl:element>
  </xsl:template>

But if I wanted to read the values, using the following template

<xsl:template match="report">
    <xsl:for-each select="book/page">
        <xsl:value-of select="@id"/>
    </xsl:for-each>
</xsl:template>

Could I chain that template to the output of the first two?

Thanks in advance,

-R.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is it possible to remove xml attributes from XSLT AND work with the resulting transform?

Yes, just search for "multi-pass transformation" and you'll find many answers with good code examples.

However, for what you want to do such transformation chaining is overly complex and completely unnecessary.

Just use:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:x="abc123" >
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="x:page">
  <xsl:value-of select="@id"/>
 </xsl:template>
</xsl:stylesheet>

And in case the default namespace of the XML document isn't known in advance, you can still produce the wanted results in a single pass:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="*[name()='page']">
  <xsl:value-of select="@id"/>
 </xsl:template>
</xsl:stylesheet>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...