0

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?

exebook
  • 32,014
  • 33
  • 141
  • 226
AlexPandiyan
  • 4,467
  • 2
  • 14
  • 11
  • Did you mean to write "Xpath"? Note that `for xml path` is something quite different: http://msdn.microsoft.com/en-us/library/ms189885. – Mathias Müller Nov 25 '13 at 10:50
  • yea i mean xpath.... i need 2 and 4 p tag becuase it have one span child so i need find that exact p tag.... – AlexPandiyan Nov 25 '13 at 11:04
  • I understood that you intend to select nodes at random (see my answer). But your question is not quite comprehensible I have to say. Show the text to someone proficient in English if possible. – Mathias Müller Nov 25 '13 at 11:10
  • my question is select paragraph tag in my xml file but that tag have one child as span tag.. so I need select result as 2 p tag and 4 p tag because that tag keep one child only, so I trying by xpath.. so can you please help this selectors... – AlexPandiyan Nov 25 '13 at 11:18

2 Answers2

1

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>
Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
0

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.

Community
  • 1
  • 1
Mathias Müller
  • 22,203
  • 13
  • 58
  • 75