In the generated code, how to access the faces declared in the XSD file?

What I thought was a simple problem turned out to be quite a puzzle.

I am currently using JAXB 2 to generate code from XSD on which I have no control. I need to access the restrictions from the circuits, so I can apply some logic and security codes when setting values ​​in these objects. Bulk validation simply will not. In most cases, I can just trim the string and everything will be fine. To do this, I need to get the length declared in XSD in order to apply it in the security code and save this common layer. An alternative is copying and hard-coding lengths, but frankly, if there was a better way to do this, I would really appreciate it.

I am talking about line length here, but this applies to all faces declared in XSD.

Suggestions, code examples, and links are welcome, basically everything that helps me NOT hardcode the data in classes.

thanks

+4
source share
2 answers

I ran into a similar problem, and the best solution I found was to write my own XJC plugin. The XJC plugin has access to both the XML schema and the generated classes, so it seemed like the easiest way to get information about the constraint. My plugin added annotation to any field in the generated class, with restrictions applied to it in the schema. For example, an element such as

<xs:element name="text"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="20" /> </xs:restriction> </xs:simpleType> </xs:element> 

will appear as

 @XmlRestrictions(maxLength = 20) protected String text; 

in the generated class file. You can then use reflection to extract constraint information from the field.

The documentation for creating the plugin is not too large, but I found this article useful. Take a look at the source code The default plugin to see how to deploy XJC to - a representation of the XML schema memory and the generated class structure. The JAXB , XSOM, and CodeModel APIs will also be useful.

+4
source

The XSD seems to contain semantic “guidelines” instead of clear rules. IMHO, if the XSD is agreed, non-compliance with this leads to a violation.

If this is not the case, and the XSD contains recommendations that need to be interpreted, I would take the time to understand the XSD parsing API analysis and try to solve the problem this way. There is no need to create new wheels.

I would, however, question the approach and try to agree on clear rules inside the XSD.

+1
source

Source: https://habr.com/ru/post/1310334/


All Articles