代码之家  ›  专栏  ›  技术社区  ›  OMG Ponies

XSLT:是否始终将特定元素添加到根目录?

  •  0
  • OMG Ponies  · 技术社区  · 15 年前

    我遇到过这样一种情况,即在遇到特定元素(xs:simpleType、xs:complexType)时,将它们放置在输出中:

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:complexType name="HighSchoolType">
        <xs:sequence>
            <xs:element name="OrganizationName" type="core:OrganizationNameType"/>
            <xs:element name="OPEID" type="core:OPEIDType"/>
            <xs:simpleType name="OPEIDType"/>
        </xs:sequence>
      </xs:complexType>
      <xs:simpleType name="OrganizationNameType"/>
    </xs:schema>
    

    我更希望xs:simpleType始终附加到根目录,无论在源代码中的何处遇到该模式。即:

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:complexType name="HighSchoolType">
        <xs:sequence>
            <xs:element name="OrganizationName" type="core:OrganizationNameType"/>
            <xs:element name="OPEID" type="core:OPEIDType"/>
        </xs:sequence>
      </xs:complexType>
      <xs:simpleType name="OrganizationNameType"/>
      <xs:simpleType name="OPEIDType"/>
    </xs:schema>
    

    在这一点上是否也可以停止重复?

    以下是我当前使用的模板:

    <xsl:template match="xs:simpleType">
        <xsl:copy>
            <xsl:copy-of select="*[not(self::xs:annotation or self::xs:restriction)]|@*"/>
        </xsl:copy>
    </xsl:template>
    
    1 回复  |  直到 15 年前
        1
  •  1
  •   steamer25    15 年前

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xsl:template match="/xs:schema">
            <xsl:copy>
                <xsl:apply-templates/>
                <xsl:copy-of select="//xs:simpleType"/>
            </xsl:copy>
        </xsl:template>
    
        <xsl:template match="*[name()!='xs:simpleType' and name()!='xs:schema']">
            <xsl:copy>
                <xsl:apply-templates select="*|@*"/>
            </xsl:copy>
        </xsl:template>
    
        <xsl:template match="@*">
            <xsl:copy-of select="."/>
        </xsl:template>
    </xsl:stylesheet>