Reputation: 4655
How to get single child node?
<root>
<p><span>text</span><span>text</span><span>text</span></p>
<p><span>text</span></p>
<p><span>text</span><span>text</span><span>text</span></p>
<p><span>text</span></p>
</root>
for example: /root/p/span
I can get all span
tag and I can find the first child or last child or child, but I need to find one child para randomly. How can I get that para tag by XML path?
Upvotes: 0
Views: 219
Reputation: 22617
Based on your clarifications, this is how you can select p
elements only if they contain exactly one span
element.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="root">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="p[count(span)=1]">
<xsl:copy>
<xsl:copy-of select="*|text()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*"/>
</xsl:stylesheet>
Input XML I used:
<?xml version="1.0" encoding="utf-8"?>
<root>
<p>
<span>wrong</span>
<span>wrong</span>
<span>wrong</span>
</p>
<p>
<span>right</span>
</p>
<p>
<span>wrong</span>
<span>wrong</span>
<span>wrong</span>
</p>
<p>
<span>right</span>
</p>
</root>
Output XML:
<?xml version="1.0" encoding="UTF-8"?>
<p>
<span>right</span>
</p>
<p>
<span>right</span>
</p>
Upvotes: 1
Reputation: 22617
Randomly choosing items is not part of standard XSLT as such because it is a functional language. In other words, it is guaranteed that you arrive at the same output for a given input no matter how many times you try.
However, if randomness is essential to you, use extensions to XSLT. Answers are suggested here:
Dimitre's libraries referenced there could be exactly what you need. Note that the precondition for random assignment is a random number and therefore that is the focus of discussion.
Upvotes: 0