XML Tutorial/XPath/parent

Материал из Web эксперт
Перейти к: навигация, поиск

returns the name of the parent element

   <source lang="xml">

File: Data.xml <?xml version = "1.0"?> <product>

  <books>
     <book>
        Getting Started with Microsoft Visual C++ 
     </book>
     <book>C How to Program</book>
  </books>

</product> File: Transform.xslt <?xml version = "1.0"?> <xsl:stylesheet version="1.0"

 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="/product">
   <xsl:value-of
     select="name(//parent::node()[. = "C How to Program"])" />
 </xsl:template>

</xsl:stylesheet> Output: <?xml version="1.0" encoding="UTF-8"?>book</source>


Selecting a Node"s Parent or Siblings

   <source lang="xml">

The .. is often combined with the attribute axis to find the attribute of the parent node (../@name). You can use an asterisk as a wildcard within the path. For example, /*/A would select all the A elements of all of the siblings of the current node.

File: Data.xml <?xml version="1.0"?> <employee>

 <name language="English">T1</name>
 <name language="Latin">T2</name>
 <projects>
   <project>project1</project>
   <project>destruction</project>
   <project>medicine</project>
 </projects>
 <weight>3 points</weight>

</employee>

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

 version="1.0">
 <xsl:template match="projects">
    <xsl:value-of select="../name[@language="English"]" /> <xsl:for-each select="project">
  • <xsl:value-of select="." />
  •      </xsl:for-each>
    
 </xsl:template>

</xsl:stylesheet>

Output: <?xml version="1.0" encoding="UTF-8"?>

 T1
 T2
    T1
  • project1
  • destruction
  •      medicine 
    
 3 points</source>
   
  

The parent axis is used to select the parent node of the context node.

   <source lang="xml">

File: Data.xml <?xml version="1.0" encoding="utf-8"?>

   <AAA id="a1" pos="start">
     <BBB id="b1"/>
     <BBB id="b2"/>
   </AAA>
   <AAA id="a2">
     <BBB id="b3"/>
     <BBB id="b4"/>
     <CCC id="c1">
       <CCC id="c2"/>
     </CCC>
     <BBB id="b5">
       <CCC id="c3"/>
     </BBB>
   </AAA>

File: Transform.xslt <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet

     version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="/">
<xsl:for-each select="/source//*"> <xsl:call-template name="print"/> </xsl:for-each> </table> </xsl:template> <xsl:template name="print"> <tr> <td> <xsl:value-of select="name()"/> <xsl:text> id = </xsl:text> <xsl:value-of select="./@id"/> </td> <td> <xsl:for-each select="parent::*"> <xsl:if test="not(@id)"> <xsl:value-of select="name()"/> </xsl:if> <xsl:value-of select="./@id"/> <xsl:text/> </xsl:for-each> </td> </tr> </xsl:template> </xsl:stylesheet> Output: <?xml version="1.0" encoding="UTF-8"?>
Axis: parent
Element</th>
         <td>Node-set</th>
</table></source>
Axis: parent
Element</th><td>Node-set</th>