XML to XML conversion with XSLT (Add, delete, modify)

£可爱£侵袭症+ 提交于 2019-12-06 20:03:28

In 90% of XSLT questions, the greatest challenge, is not the technical aspect of the question, but rather how to articulate the rules of transformation in the form of match pattern and corresponding output. Rather than give you a style-sheet, I'll give you a pattern & output view of your question. You should be able to make a style-sheet from this. There are no special techniques involved.

Comparing your input and output documents, I would describe the rules of transformation as follows.

  1. Copy the input document to the output with the following exceptions.
  2. Precede the <body> with the following literals

    <script type="t/j" src="pqr.js" />
    <script type="t/j" src="pqr.js" />
    
  3. Append to the <body> element attributes @onload="load()" and @onunload="unload()".

  4. For any <div> elements that have @id=123, change @class to QT and id to 456.
  5. For any <script> elements change @src="xyz.js" to "lmn.js".
  6. For any <script> elements in the body with @src="abc.js", delete.
  7. Wrap any <div> elements that have @class="iD" in a <form> and just before the close of the form, include the following literals

    <br/><input type="submit" name="sub" value="Done"/>
    
  8. Replace any <div> elements with @id="ta12" with this replacement:

    <div id="pa" value="10" />
    
  9. Copy any <div class="iDev">, except replace its children with the following literals

    <div id="ta8" class="bl" style="dis:bl">XYZ</div>
    <br/>
    <input type="radio" name="ke8" value="0" />
    <div id="tab8" class="bl" style="dis:bl">T</div>
    <input type="radio" name="ke8" value="1" />
    <div id="tab8" class="bl" style="dis:bl">F</div>
    

Update

The OP has asked for a template for point 5. So here it is. This is a general solution on how to copy a node, just changing one attribute ...

<xsl:template match="xhtml:script[@src='xyz.js']">
 <xsl:copy>
  <xsl:apply-templates select="@*[not(@src)]" />
  <xsl:attribute name="src">lmn.js</xsl:attribute>
  <xsl:apply-templates select="node()" />
 </xsl:copy>
</xsl:template>

If you didn't mind having a less general solution and could afford to assume that the script element would have no children and only one other attribute @type="t/j" , you could for example, use a more concise and specific template like so (but I would not recommend it - I am just laying out your options ...

<xsl:template match="xhtml:script[@src='xyz.js']">
 <xhtml:script type="t/j" src="lmn.js" />
</xsl:template>

And for point 6 it is ...

<xsl:template match="xhtml:body//xhtml:script[@src='abc.js']" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!