开发者

Get all <PRO>-Tags in different layers

i got a XML Document like this:

<PUB>
   <PGR>
      <PGR>
         <PGR>
            <PRO>
            <PRO>
            <PRO>
         </PGR>
         <PRO>
         <PRO>
     ....

So the PRO tags are in different layers, but I want to access all PRO tags. Ho开发者_如何学JAVAw do I do that?


Because this question is tagged XSLT, you might want:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/*">
        <xsl:apply-templates select=".//PRO"/>
    </xsl:template>

    <xsl:template match="PRO">
     <!-- enjoy PRO -->
    </xsl:template>

</xsl:stylesheet>

Note that differently from normal situations, the use of . in applying templates here is relevant. In fact, in this way we select all PRO elements starting from the current matching node (PUB), while:

   <xsl:apply-templates select="//PRO"/>

will apply templates to all PRO elements matching from the document root whatever the current node is.


<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="no"/>

    <xsl:template match="/">
        <xsl:apply-templates select="//PRO"/>
    </xsl:template>

    <xsl:template match="PRO">
        <xsl:value-of select="generate-id()"/>
        <xsl:text>&#xA0;</xsl:text>
    </xsl:template>

</xsl:stylesheet>


Use this XPath expression:

//PRO

This selects all elements in the XML document that are named PRO.

According to the XPath 1.0 W3C Recommendation,

// is short for /descendant-or-self::node()/

Therefore, the above XPath expression is equivalent to the longer:

/descendant-or-self::node()/PRO

It is generally recommended whenever possible to avoid the use of the // pseudooperator as it causes the complete XML document to be scanned. Whenever possible. use as much context as possible to construct a more specific XPath expression so that it can be evaluated more efficiently.

For example, if in a given XML document it is clear that the wanted element c can be selected using the XPath expression:

/a/b/c

use it and never use:

//c

The difference in execution speed sometimes be in the order of hundreds or thousands times.

Alternatively, in XSLT use just template pattern matching -- this might be the shortest transformation that accesses and processes all (and only) PRO elements in any XML document:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:template match="PRO">
  <!-- Your code here -->
 </xsl:template>

 <xsl:template match="text()"/>
</xsl:stylesheet>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜