XML Tutorial/XPath/parent — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 08:26, 26 мая 2010
returns the name of the parent element
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
Selecting a Node"s Parent or Siblings
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">
<ul>
<xsl:value-of select="../name[@language="English"]" />
<xsl:for-each select="project">
<li>
<xsl:value-of select="." />
</li>
</xsl:for-each>
</ul>
</xsl:template>
</xsl:stylesheet>
Output:
<?xml version="1.0" encoding="UTF-8"?>
T1
T2
<ul>T1<li>project1</li><li>destruction</li><li>
medicine
</li></ul>
3 points
The parent axis is used to select the parent node of the context node.
File: Data.xml
<?xml version="1.0" encoding="utf-8"?>
<data>
<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>
</data>
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="/">
<table border="1" cellpadding="6">
<tr>
<th colspan="2">Axis: parent</th>
</tr>
<tr>
<td>Element</th>
<td>Node-set</th>
</tr>
<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"?><table border="1" cellpadding="6"><tr><th colspan="2">Axis: parent</th></tr><tr><td>Element</th><td>Node-set</th></tr></table>