Domanda

Ho un file XML nel seguente formato:

<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>

Devo usarlo su un controllo TreeView standard .net 2.0 che richiede l'XML nel seguente formato

<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>

La più grande complicazione è il fatto che alcuni nodi figlio del nodo DOCTYPE devono essere convertiti in attributi (ad esempio NOME) mentre alcuni rimangono nodi figlio che richiedono attributi propri (ad esempio SITO).

Come si può fare usando XSLT?

È stato utile?

Soluzione

La seguente trasformazione XSLT 1.0 fa ciò che intendi.

<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>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top