Home > Mobile >  How do I access an <Any>-element in xslt?
How do I access an <Any>-element in xslt?

Time:12-02

I have the following xsd schema:

<Person>
 <Gender>
 <Any>

I have the following xml:

<Person>
 <Gender>Male</Gender>
 <Name>
  <firstName>Elon</firstName>
  <lastName>Musk</lastName>
</Name>
</Person>

I want to print the the text "Tesla" if the lastname is equal to "Musk".
I started with a template-match but I cannot access the Any-element.

Any good suggestions on how to access an -element in xslt?

I tried writing an template-match for this but I was not able to access the Any-element as expected.

<xsl:template match="/Person//* = 'Musk'">
    <text>Tesla</text>
  </xsl:template>

CodePudding user response:

To access the element in your XSLT, you would use the xsl:value-of element and specify the path to the element in the select attribute. Here is an example of how you could do this:

<xsl:template match="/Person">
  <xsl:if test="Name/lastName = 'Musk'">
    <text>Tesla</text>
  </xsl:if>
</xsl:template>

In this example, the xsl:if element is used to test if the lastName element is equal to Musk. If this is true, the Tesla element is printed.

You could also use the xsl:value-of element to directly access the text value of the element, like this:

<xsl:template match="/Person">
  <xsl:if test="Name/lastName = 'Musk'">
    <xsl:value-of select="Any" />
  </xl:if>
</xsl:template>

This will print the text value of the element if the lastName element is equal to Musk. You can then use this text value in your XSLT as needed.

CodePudding user response:

There is no Any element in your XML, so you cannot access it.

If you want your template to match a Person whose lastName is "Musk", then do:

<xsl:template match="/Person[Name/lastName='Musk*']">
    <text>Tesla</text>
</xsl:template>

If you want your template to match a Person that has some descendant element with a value of "Musk", then do:

<xsl:template match="/Person[.//*='Musk']">
    <text>Tesla</text>
</xsl:template>
  • Related