XSLT - Put Content by checking attribute

130 Views Asked by At

I'm new to XSLT. and I've a xml to xml transformation task. what I have to do is put some xml node to result xml tree by checking some attribute values in original xml file.

example :

original xml has

<doc>
<sec id="sec_1" sec-type="scope"> </sec> 
<sec id="sec_1" sec-type="norm-refs"> </sec>
//more codes
<doc>

what I need to do is,put some new xml node (as example : <c type="newaddingnode">&#x200B;</c> ) at the end of the node in to to the result xml by checking the attribute in node

eg:

if sec-type="norm-refs" is exist insert the new node at the end of the sec-type="scope". If this attribute does not exist, insert the new node at the end of the sec-type="scope". IF both sections are missing, do nothing.

so, if my original xml as follows,

<doc>
    <sec id="sec_1" sec-type="scope"> </sec> 
    //more codes
  <doc>

my result xml should be like this

<doc>
    <sec id="sec_1" sec-type="scope"> </sec> 
    <c type="newaddingnode">&#x200B;</c>
    //more codes
  <doc>

if my original xml as follows,

<doc>
    <sec id="sec_1" sec-type="norm-refs"> </sec> 
    //more codes
  <doc>

my result xml should be like this

<doc>
    <sec id="sec_1" sec-type="norm-refs"> </sec> 
    <c type="newaddingnode">&#x200B;</c>
    //more codes
  <doc>

and if both <sec id="sec_1" sec-type="norm-refs"> and <sec id="sec_1" sec-type="scope"> are not exist new node should not be added. also adding node should not be a child node of <sec>. but it should add end of the <sec> node.

in other languages this would be relatively easy task but I'm new to xslt, so I'm wondering how can I do this in XSLT. can I use <xsl:if> or <xsl:choose> to do this ?

1

There are 1 best solutions below

2
Michael Kay On BEST ANSWER

Well, I think we still don't have a full specification, but I'll try. I think you've told us (a) add a new node after any sec with @sec_type='scope'. That's

<xsl:template match="sec[@sec_type='scope']">
  <xsl:copy-of select="."/>
  <c type="newaddingnode">&#x200B;</c>
</xsl:template>

(b) add a new node after any sec with @sec_type='norm-refs'. That's

<xsl:template match="sec[@sec_type='norm-refs']">
  <xsl:copy-of select="."/>
  <c type="newaddingnode">&#x200B;</c>
</xsl:template>

Now, there are other conditions that perhaps you haven't told us about, like what happens if both are present or if one of them is present twice. Those conditions can be handled by refining the match patterns or by adding more rules.