maha
maha

Reputation: 39

How to insert a missing element or modify an existing element?

I am working on XML & XSLT dynamic value has to generate.

My XmL

<query>
     <one>testing1</one>
     <one>testing1</one>
</query>

My Output Xml

<query>
     <one>testing1</one>
     <one>testing1</one>
     <sample>100</sample>
</query>

XSLT I need to check(XSL:IF)whether sample element is available or not from Input XML if available 10% I have to remove % using XSLT then output will be 10. If there Is no element in XML(Sample) It has to create by default 100.

Can we able to do this in XSLT is that possible.

Can anyone help me out here please

Regards M

Upvotes: 0

Views: 1328

Answers (1)

Sean B. Durkin
Sean B. Durkin

Reputation: 12729

How about this ...

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="@*|node()">
   <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
   </xsl:copy>
</xsl:template>

<xsl:template match="/*[not(//sample)]">
   <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
     <sample>100</sample> 
   </xsl:copy>
</xsl:template>

<xsl:template match="sample">
   <xsl:copy>
    <xsl:apply-templates select="@*"/>
    <xsl:value-of select="translate(.,'%','')"/>
    <xsl:apply-templates select="*"/>
   </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Explanation

The second template adds the sample node, if it was not present. The third template removes any percentage signs from existing samples.

Upvotes: 2

Related Questions