views:

62

answers:

4

Hello All, I am using xslt first time. I have to create an element based on some criteria.

here is i/p xml:

<FirstUser>
   <User id="2" description="ABC" Type="HR"/>
</FirstUser>
<SecondUser>
  <User id="3" description="ABC" Type="HR"/>
  <User id="4" description="xyz" Type="Admin"/>
  <User id="5" description="LMN" Type="Payroll"/>
</SecondUser>

Final O/P

<AllUsers isFromHR='true'>
  <User id="2" description="ABC" Type="HR"/>
  <User id="3" description="ABC" Type="HR"/>
  <User id="4" description="xyz" Type="Admin"/>
  <User id="5" description="LMN" Type="Payroll"/>
</AllUsers>

Business Rule: AllUsers element has 1 attribute isFromHR - Its value w'd be true if value in type attribute of <FirstUser> or <SecondUser> is HR else it will be false

How to populate the value of isFromHR ? Rest of xml creation I am done.

Thanks in advance.

+2  A: 

What about

<AllUsers isFromHR="{ count((//FirstUser | //SecondUser)[@type='HR']) &gt; 0 }">

or

<AllUsers>
    <xsl:attribute 
         name="isFromHR"
         value="count((//FirstUser | //SecondUser)[@type='HR']) &gt; 0" />
Rubens Farias
A: 
  <xsl:template match="/">
    <AllUsers>
      <xsl:attribute name="isFromHR">
        <xsl:choose>
            <xsl:when test="//*[local-name(.)='FirstUser' or local-name(.)='SecondUser']/*/@Type[.='HR']">true</xsl:when>
        <xsl:otherwise>false</xsl:otherwise>
      </xsl:choose>
        </xsl:attribute>
      <xsl:apply-templates />
    </AllUsers >
  </xsl:template>
Mads Hansen
Many many thanks SIR... This trick worked. I w'd be extremely happy If I could get some soft copy material to read as I am new to xslt World.I have few more queries regarding various xslt functions and use of variables... so If you could provide me some softcopy to study...will be good for me.Once again many Thanks :-)
Amit
Check out the XSLT http://www.w3schools.com/xsl/default.asp and XPATH http://www.w3schools.com/xpath/default.asp tutorials on http://w3schools.com, to get started. Dave Pawson maintains a very useful site: http://www.dpawson.co.uk/xsl/ The FAQ's distill many common problems, explainations, and code snippets.
Mads Hansen
A: 
<AllUsers isFromHR="{descendant::@type = 'HR'}">
jelovirt
A: 

The input XML is missing elements:

<FirstUser>
   <User id="2" description="ABC" Type="HqR"/>
</FirstUser>
<SecondUser>
  <User id="3" description="ABC" Type="H2R"/>
  <User id="4" description="xyz" Type="Admin"/>
  <User id="5" description="LMN" Type="Payroll"/>
</SecondUser>

In any case, I'd go for:

<AllUsers isFromHR="{//FirstUser/User/@Type = 'HR' or //SecondUser/User/@Type = 'HR'}">

This gives you "true" in case either FirstUser or SecondUser contains a User of type 'HR'.

bolk