java - 如何使用 Apache XMLBeans 从 Xsd-Schema 读取 Xsd-Annotations?

标签 java xsd xmlbeans

我使用 Apache XMLBeans 读取 xsd-schema 文件,从根元素开始迭代所有 SchemaProperties。 在每个 SchemaProperty 中,我都在寻找带有以下内容的注释:schemaProperty.getType().getAnnotation(),但我没有找到任何注释。 (下面是java代码)

我检查以下 xsd 文件:

xsd结构图:

figure of xsd structure

Xsd 源代码:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="ExterneDaten" type="ExterneDaten">
    <xs:annotation>
        <xs:documentation>annotation for ExterneDaten</xs:documentation>
    </xs:annotation>
</xs:element>
<xs:complexType name="ExterneDaten">
    <xs:annotation>
        <xs:documentation>annotation for Type ExterneDaten</xs:documentation>
    </xs:annotation>
    <xs:sequence>
        <xs:element name="value1" type="xs:string">
            <xs:annotation>
                <xs:documentation>annotation for value1</xs:documentation>
            </xs:annotation>
        </xs:element>
    </xs:sequence>
    <xs:attribute name="isTest" type="xs:boolean">
        <xs:annotation>
            <xs:documentation>annotation for boolean attribute isTest</xs:documentation>
        </xs:annotation>
    </xs:attribute>
</xs:complexType>

我用我的函数检查xsd:MyXsdReader.readAllAnnotationsFromXsd(String schema);

这是java代码:

public class MyXsdReader
{

    public static void readAllAnnotationsFromXsd(String newSchema)
    {
        try
        {
            SchemaTypeLoader loader = XmlBeans.typeLoaderForClassLoader(SchemaDocument.class.getClassLoader());

            XmlObject[] xmlObjects = new XmlObject[1];
            XmlOptions options = new XmlOptions();
            options.setLoadLineNumbers().setLoadMessageDigest().setCharacterEncoding("utf-8");
            options.setCompileDownloadUrls();
            xmlObjects[0] = loader.parse(newSchema, null, options);
            SchemaTypeSystem sts = XmlBeans.compileXsd(xmlObjects, XmlBeans.getBuiltinTypeSystem(), options);
            readXsdRootElement(sts);

        }
        catch (Exception e)
        {
            System.out.println("makeXsdListRootEle(): Excpetion: " + e.getMessage());
        }
    }

    private static void readXsdRootElement(SchemaTypeSystem sts)
    {
        SchemaGlobalElement[] globals = sts.globalElements();
        if (globals != null && globals.length == 1)
        {
            SchemaGlobalElement sge = globals[0];
            SchemaType st = sge.getType();
            SchemaProperty[] properties = st.getProperties();
            for (int k = 0; k < properties.length; k++)
            {
            SchemaProperty property = properties[k];
            checkAnnotation(property);
            if (property.isAttribute() == false)
            {
                readXsdProperty(property);
            }
            }
        }
    }

    private static void readXsdProperty(SchemaProperty property)
    {
        SchemaProperty[] properties = property.getType().getProperties();
        for (SchemaProperty schemaProperty : properties)
        {
            checkAnnotation(schemaProperty);
            readXsdProperty(schemaProperty);
        }
    }

    private static void checkAnnotation(SchemaProperty schemaProperty)
    {
        SchemaAnnotation annotation = schemaProperty.getType().getAnnotation();
        if (annotation != null)
        {
            System.out.println(annotation.toString());
        }
    }
}

我必须做什么才能读取 xsd 内的注释?

最佳答案

我有同样的要求,并且能够解析 XSD 中的注释,如下所示。

假设 XSD 如下:-

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="ExterneDaten" type="ExterneDaten">
    <xs:annotation>
        <xs:documentation>annotation for ExterneDaten</xs:documentation>
    </xs:annotation>
</xs:element>
<xs:complexType name="ExterneDaten">
    <xs:annotation>
        <xs:documentation>annotation for Type ExterneDaten</xs:documentation>
    </xs:annotation>
    <xs:sequence>
        <xs:element name="value1" type="xs:string">
            <xs:annotation>
                <xs:documentation>annotation for value1</xs:documentation>
            </xs:annotation>
        </xs:element>
    </xs:sequence>
    <xs:attribute name="isTest" type="xs:boolean">
        <xs:annotation>
            <xs:documentation>annotation for boolean attribute isTest</xs:documentation>
        </xs:annotation>
    </xs:attribute>
</xs:complexType>

现在,我们必须创建一个自定义注释解析器,如下所示:-

public class XSDAnnotaionParser extends AnnotationParser {

    private StringBuilder documentation = new StringBuilder();

    @Override
    public ContentHandler getContentHandler(AnnotationContext context, String parentElementName, ErrorHandler handler,
            EntityResolver resolver) {
        return new ContentHandler() {
            private boolean parsingDocumentation = false;

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (parsingDocumentation) {
                    documentation.append(ch, start, length);
                }
            }

            @Override
            public void endElement(String uri, String localName, String name) throws SAXException {
                //say you want to parse the text in "documentaion" tag in your xsd....this is where we scpecify the tag
                if (localName.equals("documentation")) {
                    parsingDocumentation = false;
                }
            }

            @Override
            public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException {
                if (localName.equals("documentation")) {
                    parsingDocumentation = true;
                }
            }

            @Override
            public void setDocumentLocator(Locator locator) {
                // TODO Auto-generated method stub

            }

            @Override
            public void startDocument() throws SAXException {
                // TODO Auto-generated method stub

            }

            @Override
            public void endDocument() throws SAXException {
                // TODO Auto-generated method stub

            }

            @Override
            public void startPrefixMapping(String prefix, String uri) throws SAXException {
                // TODO Auto-generated method stub

            }

            @Override
            public void endPrefixMapping(String prefix) throws SAXException {
                // TODO Auto-generated method stub

            }

            @Override
            public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
                // TODO Auto-generated method stub

            }

            @Override
            public void processingInstruction(String target, String data) throws SAXException {
                // TODO Auto-generated method stub

            }

            @Override
            public void skippedEntity(String name) throws SAXException {
                // TODO Auto-generated method stub

            }
        };
    }

    @Override
    public Object getResult(Object existing) {
        return documentation.toString().trim();
    }
}

现在我们为上面创建的自定义注释解析器创建一个工厂类,如下所示:-

class AnnotationFactory implements AnnotationParserFactory {
    @Override
    public AnnotationParser create() {
        return new XSDAnnotaionParser();
    }
}

现在我们将自定义注释解析器添加到 XSOMParser,用于解析 XSD,如下所示:-

XSOMParser parser = new XSOMParser();
parser.setAnnotationParser(new AnnotationFactory());
try {
    parser.parse(xml);
} catch (SAXException ex) {
    throw new SchemaException(ex);
}

为了解析文档标签,我们可以使用如下代码:-

XSSchemaSet schemaSet = null;
        try {
            schemaSet = parser.getResult();
        } catch (SAXException ex) {
            throw new SchemaException(ex);
        }

        Iterator<XSElementDecl> iterator = schemaSet.iterateElementDecls();
    while (iterator.hasNext()) {
        XSElementDecl elementDecl= (XSElementDecl) iterator.next();
        XSComplexType eleCompDecl= elementDecl.getType().asComplexType();
        if (eleCompDecl!= null) {
            //we get the annotation here
            XSAnnotation annotaion = eleCompDecl.getAnnotation();
            //this will print the tezxt inside documentaion tag
            System.out.println(annotaion.getAnnotation());
        }
    }

读取 xsd 属性内注释的代码如下:-

            Collection<? extends XSAttributeUse> attributes= eleCompDecl.getAttributeUses();

            Iterator<? extends XSAttributeUse> iterator = attributes.iterator();
            while(attributes.hasNext()) {

                XSAttributeUse next = attributes.next();
                XSAttributeDecl attributeDecl = next.getDecl(); 
                String desc = null;
                if(attributeDecl != null) {
                    try {
                        desc = (String)attributeDecl.getAnnotation().getAnnotation();
                        System.out.println("the documentaion for the attribute is "+desc)
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

关于java - 如何使用 Apache XMLBeans 从 Xsd-Schema 读取 Xsd-Annotations?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48196744/

相关文章:

python - 使用 Python 将 XSD(XML Schema)转换为 AVSC(Avro Schema)

java - 如何让JAXB正确生成XML?

java - 从 sax validator 获取更多信息

java - 游戏失去焦点后计时器不会恢复

java - JList:显示存储以外的其他内容

java - 如何向flink CEP数据流添加新事件?

jaxb - 如何在 enunciate 中记录类型?

java - 没有为 XSD 和 WSDL 文件生成 XMLBean 类 (Maven)

java - 如何将 XmlCursor 内容插入 DOM 文档

Java 8 语法令人难以理解