1

我有一个 XML 文件,格式如下:

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

我需要在标准 .net 2.0 TreeView 控件上使用它,该控件需要以下格式的 XML

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

最大的复杂性是 DOCTYPE 节点的一些子节点需要转换为属性(即 NAME),而有些则保留为需要它们自己的属性的子节点(即 SITE)。

如何使用 XSLT 做到这一点?

4

1 回答 1

3

以下 XSLT 1.0 转换符合您的预期。

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

输出:

<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>
于 2009-03-18T12:31:46.093 回答