开发者

How to Count the all <w:p> nodes(inside <w:body>)of my current Node using XSLT 2.0?

开发者 https://www.devze.com 2023-04-08 06:21 出处:网络
This is my Xml File <w:body> <w:p><w:r><w:t>para1</w:t></w:r></w:p>

This is my Xml File

<w:body> <w:p><w:r><w:t>para1</w:t></w:r></w:p>
 <w:p><w:r><w:t>para2</w:t></w:r></w:p>
 <w:p><w:r><w:t>para3</w:t></w:r></w:p>
 <w:p><w:r><w:t>para4</w:t></w:r></w:p>
 <w:p><w:r><w:t>para5</w:t></w:r></w:p>
 <w:tbl><w:tr><w:tc><w:p><w:r><w:t>para6</w:t></w:r></w:p></w:tc>

 <w:tc><w:p><w:r><w:t>para7</w:t></w:r></w:p></w:tc>   <!-- Ass开发者_运维百科ume This
 is my Current Node -->

 <w:tc><w:p><w:r><w:t>para8</w:t></w:r></w:p></w:tc>
              </w:tr> </w:tbl> </w:body>

So, Now i want to get the count of all <w:p> inside <w:body> and also previous <w:p> of the current node inside <w:tbl>. So, For this scenario, my Expected count is 7 at this time...

how i do it?help me to get this...


Use:

count($vtheNode/preceding::w:p)

where $vtheNode is your node.

XSLT (both 1.0 and 2.0) solution:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:w="w:w">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:variable name="vtheNode" select=
    "/w:body/w:tbl/w:tr/w:tc[last()]"/>

 <xsl:template match="/">
     <xsl:value-of select="count($vtheNode/preceding::w:p)"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document (with namespace defined to make it well-formed):

<w:body xmlns:w="w:w">
    <w:p>
        <w:r>
            <w:t>para1</w:t>
        </w:r>
    </w:p>
    <w:p>
        <w:r>
            <w:t>para2</w:t>
        </w:r>
    </w:p>
    <w:p>
        <w:r>
            <w:t>para3</w:t>
        </w:r>
    </w:p>
    <w:p>
        <w:r>
            <w:t>para4</w:t>
        </w:r>
    </w:p>
    <w:p>
        <w:r>
            <w:t>para5</w:t>
        </w:r>
    </w:p>

    <w:tbl>
        <w:tr>
            <w:tc>
                <w:p>
                    <w:r>
                        <w:t>para6</w:t>
                    </w:r>
                </w:p>
            </w:tc>
            <w:tc>
                <w:p>
                    <w:r>
                        <w:t>para7</w:t>
                    </w:r>
                </w:p>
            </w:tc>
            <!-- Assume This  is my Current Node -->
            <w:tc>
                <w:p>
                    <w:r>
                        <w:t>para8</w:t>
                    </w:r>
                </w:p>
            </w:tc>
        </w:tr>
    </w:tbl>
</w:body>

the wanted, correct result is produced:

7

Do note: Because the preceding:: and ancestor:: axes are not overlapping, a more general solution that doesn't depend on the structure of the document and takes into account the possibility that some of the wanted to count nodes could be ancestors, is:

count($vtheNode/preceding::w:p | ($vtheNode/ancestor::w:p)
0

精彩评论

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

关注公众号