1

I have an XML file which is in the following format:

<root>
  <category>
    <doctype>
      <name>Doc1</name>
      <site>
        <name>Site1</name>
        <target>iframe</target>
        <url>http://www.gmail.com</url>
      </site>
    </doctype>
    <doctype>
      <name>Doc2</name>
      <site>
        <name>Site2</name>
        <target>iframe</target>
        <url>http://www.bbc.co.uk</url>
      </site>
    </doctype>
  </category>
</root>

I need to use it on a standard .net 2.0 TreeView control which requires the XML in the following format

<root>
  <category>  
    <doctype name="Doc1">
      <site name = "Site1" target = "iframe" url = "http://www.gmail.com">
      </site>
    </doctype>
    <doctype name="Doc2">
      <site name = "Site2" target = "iframe" url = "http://www.bbc.co.uk">
      </site>
    </doctype>
  </category>
</root>

The biggest complication is the fact that some child nodes of the DOCTYPE node need to be converted to attributes (i.e. NAME) while some stay as child nodes which require attributes of their own (i.e. SITE).

How can this be done using XSLT?

3
  • If you can settle on a consistent case for names the transformation in my answer would become a lot simpler. Also I am a bit unsure if your input XML really has quotes. Can you confirm that as well? Commented Mar 18, 2009 at 13:01
  • apologies, i knocked that up trying to mimic what i actually get but didnt pay attention to the case & forgot about the quotes. Commented Mar 18, 2009 at 14:16
  • I changed my answer to fit your new question. You will find that it is a lot simpler now. Commented Mar 18, 2009 at 14:58

1 Answer 1

3

The following XSLT 1.0 transformation does what you intend.

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="root | category | doctype | site">
    <xsl:copy>
       <xsl:apply-templates select="*" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="name | target | url">
    <xsl:attribute name="{local-name()}">
      <xsl:value-of select="." />
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>

Output:

<root>
  <category>
    <doctype name="Doc1">
      <site name="Site1" target="iframe" url="http://www.gmail.com"></site>
    </doctype>
    <doctype name="Doc2">
      <site name="Site2" target="iframe" url="http://www.bbc.co.uk"></site>
    </doctype>
  </category>
</root>
Sign up to request clarification or add additional context in comments.

1 Comment

would apprecaite the simpler solution for the modified question. thanks

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.