About root node in xslt

2019-08-14 17:19发布

问题:

I am new to xslt.

Kindly see the below cases :

Input :

<?xml version="1.0"?>
         <Hello>
          <hi>
           <hii>
            shashi
           </hii>
          </hi>
         </Hello>

Case 1 :

Xslt Code :

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

    <xsl:template match="/">
    <xsl:copy-of select="."/>
    </xsl:template>

</xsl:stylesheet>

Output for Case 1 :

<?xml version="1.0"?>
<Hello>
<hi>
<hii>
shashi
</hii>
</hi>
</Hello>

Case 2 :

Xslt code :

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

<xsl:template match="/">
<xsl:copy-of select="./hi"/>
</xsl:template>
</xsl:stylesheet>

In case 2 there is no output shown.I am not getting why ?

<xsl:template match="/">

when this points to the root node that is Hello.Therefore in case 1 when it executes

<xsl:copy-of select="."/>

This will print the entire xml.

In case 2 : when it executes

<xsl:copy-of select="./hi"/>

it should print below.

<hi>
    <hii>
    shashi
    </hii>
    </hi>

Can somebody please help on this?

Thanks, Shashiraj NK

回答1:

You need to be aware of variations in terminology here. In all the tree models I know of, there are two relevant nodes: one representing the element Hello (which I call the "outermost element", hopefully to avoid confusion), plus its parent, which represents the document as a whole: let's call that the "container" for the moment.

The XML specification itself doesn't define a tree model, but it does say "There is exactly one element, called the root, or document element" - which is the source of much of the confusion.

The DOM calls the container a Document node (or, just to add complications, a DocumentFragment in the case where it's not a well-formed document with a single outermost element). And it calls the outermost element the "document element" - which at least has the merit of matching the terminology in the XML specification.

In XPath 1.0 (and therefore XSLT 1.0), the container is called the "root node", and the spec uses the term "document element" for the outermost element, though it doesn't play a very significant role, largely because the model supports document nodes having multiple element children.

In XPath 2.0 (and XSLT 2.0) you can construct trees in which the root of the tree can be any kind of node, for example you can have an element with no parent. So there is a change in terminology: a "root" is now a node (of any kind) having no parent, while what I have called the "container" representing a document as a whole is now called the "document node".

But whether you are using XPath 1.0 or 2.0, /* matches the Hello element, and / matches its parent node, which is the root of the tree.



回答2:

/ selects the root node which is the document node containing all other nodes. The root element is selected by /*.



标签: xml xslt