0

How can i add the element(date) to the Level1 element as an attribute

below is the Source xml

<level>
  <date> 2019-jan-01<date>
  <level1 name ="abc", age = 24>
    <level2 val1 = "asd"> 2.34</level2>
 </level1>
  <level1 name ="abc", age = 24>
    <level2 val1 = "asd"> 2.34</level2>
 </level1>
</level>

Target XML

<level>
  <level1 name ="abc", age = 24 , date = 2019-jan-01 >
    <level2 val1 = "asd"> 2.34</level2>
 </level1>
  <level1 name ="abc", age = 24 , date = 2019-jan-01>
    <level2 val1 = "asd"> 2.34</level2>
 </level1>
</level>
0

1 Answer 1

2

The source XML needs to be cleaned up a bit--remove commmas, add quotes, etc.:

<level>
  <date>2019-jan-01</date>
  <level1 name="abc" age="24">
    <level2 val1="asd">2.34</level2>
  </level1>
  <level1 name="abc" age="24">
    <level2 val1="asd">2.34</level2>
 </level1>
</level>

Then this XSLT will transform the source to your target:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.1">

  <!-- exclude the date element -->
  <xsl:template match="date" />

  <!-- copy the level1 element adding an attribute -->
  <xsl:template match="level1">
    <xsl:copy>
      <xsl:attribute name="date">
        <xsl:value-of select="../date/text()"/>
      </xsl:attribute>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- keep everything the same unless explicit transformed by above -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

The result is:

<level>
  <level1 date="2019-jan-01" name="abc" age="24">
    <level2 val1="asd">2.34</level2>
  </level1>
  <level1 date="2019-jan-01" name="abc" age="24">
    <level2 val1="asd">2.34</level2>
 </level1>
</level>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.