代码之家  ›  专栏  ›  技术社区  ›  chansey

如何在实例文档中使用xpath按xsd类型选择元素?

  •  1
  • chansey  · 技术社区  · 8 年前

    例如: 我的xsd是:

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
        <xs:element name="Zoo">
            <xs:complexType>
                <xs:sequence maxOccurs="unbounded">
                    <xs:element ref="Animal"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
        <xs:element abstract="true" name="Animal"/>
        <xs:element name="Tiger" substitutionGroup="Animal" type="Tiger"/>
        <xs:element name="Wolf" substitutionGroup="Animal" type="Wolf"/>
        <xs:complexType name="Animal">
            <xs:attribute name="name"/>
        </xs:complexType>
        <xs:complexType name="Tiger">
            <xs:complexContent>
                <xs:extension base="Animal"/>
            </xs:complexContent>
        </xs:complexType>
        <xs:complexType name="Wolf">
            <xs:complexContent>
                <xs:extension base="Animal"/>
            </xs:complexContent>
        </xs:complexType>
    </xs:schema>
    

    我的实例文档是:

    <Zoo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Zoo.xsd">
        <Tiger name="001"/>
        <Wolf name="002"/>
        <Wolf name="003"/>
    </Zoo>
    

    如何使用xpath选择复杂类型为Animal的所有元素? xpath能够使用xsd元信息吗?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Martin Honnen    8 年前

    使用支持模式的处理器(如Saxon 9 EE或Altova XMLSpy/Raptor),您可以使用 //element(*, Animal) ( https://www.w3.org/TR/xpath-31/#doc-xpath31-ElementTest )选择该类型的所有图元 Animal ,样式表如下所示

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:math="http://www.w3.org/2005/xpath-functions/math"
        exclude-result-prefixes="xs math"
        version="3.0">
    
        <xsl:import-schema schema-location="Zoo.xsd"/>
    
        <xsl:template match="/">
            <xsl:copy-of select="//element(*, Animal)"/>
        </xsl:template>
    
    </xsl:stylesheet>