Apache Xerces 获取 xsd 中每个元素的声明

Apache Xerces get declaration of every element in xsd

我正在使用 Apache Xerces 解析以下 XSD 文件。

<xs:element name="Root" type="RootType">
    ...
</xs:element>

<xs:complexType name="RootType">
    <xs:complexContent>
        <xs:extension base="BaseElement">
            <xs:choice maxOccurs="unbounded">
                <xs:element name="ElementA" type="ElementAType" />
                <xs:element name="ElementB" type="ElementBType" />
                <xs:element name="ElementC" type="ElementCType" />
            </xs:choice>

            <xs:attribute ... >...</xs:attribute>
            <xs:attribute ... >...</xs:attribute>
            <xs:attribute ... >...</xs:attribute>
        </xs:extension>
    </xs:complexContent>
</xs:complexType>

<xs:complexType name="BaseElement">
    ...
</xs:complexType>

<xs:complexType name="ElementAType">
    ...
</xs:complexType>

<xs:complexType name="ElementBType">
    ...
</xs:complexType>

<xs:complexType name="ElementCType">
    ...
</xs:complexType>

我想获取文件中每个元素的声明,即:Root、ElementA、ElementB 和 ElementC。方法:

XSElementDeclaration decl = model.getElementDeclaration("ElementA");

returns ElementA、ElementB 和 ElementC 为空。它只找到根元素的声明。

XSNamedMap comp = model.getComponents(XSConstants.ELEMENT_DECLARATION);

也不行,它returns只是根声明。 如何让这些声明嵌套在 RootType 中?

您必须递归地搜索架构组件模型。从全局元素声明 (XSElementDeclaration) getTypeDefinition() 获取 XSComplexTypeDefinition。从那里递归地使用 getParticle() 和 getTerm() 最终会让你得到代表局部元素声明的 XSElementDeclaration 对象。

(Saxon SCM 文件包含基本相同的数据结构,但采用 XML 格式,这使您可以使用 XPath 表达式更方便地进行搜索,而不是逐步的过程导航。)