Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add/insert child element(s) using XSLT

Tags:

xml

xslt

i have the following situation:

i need to add child element(s) to an existing XML tag.

my current XML looks like this, it contains an empty (self-closing) "<attr tag=.../>":

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
...
<attr tag="00081110" vr="SQ" pos="-1" name="Referenced Study Sequence" len="-1"/>
...
</dataset>

after transformation it should look something like this, with 2 child elements added/inserted (envelopped by a <item> element):

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
...
<attr tag="00081110" vr="SQ" pos="-1" name="Referenced Study Sequence" len="-1">
  <item id="1" pos="28" len="-1">
    <attr tag="00081150" vr="UI" pos="36" name="Referenced SOP Class UID" vm="0" len="3">991</attr>
    <attr tag="00081155" vr="UI" pos="44" name="Referenced SOP Instance UID" vm="0" len="3">992</attr>
  </item>
</attr>

...
</dataset>

how can i achieve this? i have tried various random setups but in my best shot i ended up by replacing the parent element (tag="00081110") with a child element.

like image 653
svenson Avatar asked Sep 20 '13 08:09

svenson


People also ask

What is text () in XSLT?

The <xsl:text> element is used to write literal text to the output. Tip: This element may contain literal text, entity references, and #PCDATA.

What is Number () in XSLT?

Specifies the format pattern. Here are some of the characters used in the formatting pattern: 0 (Digit) # (Digit, zero shows as absent)

What is current group () in XSLT?

Returns the contents of the current group selected by xsl:for-each-group. Available in XSLT 2.0 and later versions. Available in all Saxon editions. current-group() ➔ item()*


1 Answers

<xsl:template match="attr">
  <xsl:copy>
    <xsl:copy-of select="@*" />

    <item id="1" pos="28" len="-1">
      <attr tag="00081150" vr="UI" pos="36" name="Referenced SOP Class UID" vm="0" len="3">991</attr>
      <attr tag="00081155" vr="UI" pos="44" name="Referenced SOP Instance UID" vm="0" len="3">992</attr>
    </item>

  </xsl:copy>
</xsl:template>
like image 52
Tomalak Avatar answered Oct 07 '22 23:10

Tomalak