Parsing XSD and getting nested elements

偶尔善良 提交于 2019-12-25 04:19:27

问题


After going through this page, I wrote the following code to parse an XSD file. However I only get the root element, and I am lost so as to how to get the nested elements inside it. Code:

            XMLSchemaLoader loader = new XMLSchemaLoader();
            XSModel model = loader.loadURI(url.toURI().toString());
            XSNamedMap map = model.getComponents(XSConstants.ELEMENT_DECLARATION);  //returns the root component 

            if(map!=null ){
                for (int j=0; j<map.getLength(); j++) {
                   String name = map.item(j).getName(); //returns 'country' correctly.                    
                }
            }

I am not posting the entire xsd, but this is the structure:

<xsd:element name="country">
    <xsd:complexType>
        <xsd:annotation>
                <xsd:appinfo id="substring">No</xsd:appinfo>                                                
        </xsd:annotation>
        <xsd:sequence minOccurs="1" maxOccurs="unbounded">
            <xsd:element name="states"  minOccurs="1" maxOccurs="1" >
                <xsd:complexType>
                    <xsd:annotation>
                            <xsd:appinfo id="substring">No</xsd:appinfo>                                                
                    </xsd:annotation>
                    <xsd:sequence>
                        <xsd:element name="cities" minOccurs="1" maxOccurs="unbounded">
                        </xsd:element>
                    </xsd:sequence>
                    <xsd:attribute name="name" type="xsd:string" />
                </xsd:complexType>
            </xsd:element>
        </xsd:sequence>
        <xsd:attribute name="name" type="xsd:string"></xsd:attribute>
    </xsd:complexType>
</xsd:element>

I am looking to read all the elements, not just the base element, and not sure how to proceed. Thanks for the help.


回答1:


I think your trying to iterate over the XSNamedMap incorrectly. The reason you are getting only the country element is because it is the root element. You will probably have to descend down into XSNamespaceItem and call getComponents to retrieve another set of XSNamedMap objects.

This will properly parse the XSD but you still have to traverse the tree.



来源:https://stackoverflow.com/questions/8069358/parsing-xsd-and-getting-nested-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!