开发者

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

What I thought was going to be a simple problem turns out to be quite a head scratcher.

I am currently using JAXB 2 to generate code from an XSD on which I have no control. I need to access the constraints from the schemas so I can apply some logic and guard code when setting values in these objects. Validation in bulk simply will n开发者_如何转开发ot do. In most cases I can simply truncate the string and all will be good. For this I need to get the length that was declared in the XSD in order to apply it in the guard code and keep this layer generic. The alternative is to copy and hard code the lengths but frankly if there was a better way to do this I would really appreciate.

I speak of string length here but this applies to all facets declarable in an XSD.

Suggestions, Code samples and links welcome, basically anything that would help me NOT hard code the data in the classes.

Thanks


I was faced with a similar problem and the best solution I found was to write my own XJC plugin. An XJC plugin has access to both the XML schema and the generated classes, so it seemed like the easiest way to get at the restriction information. My plugin added an annotation to any field in the generated class that had restrictions applied to it in the schema. For instance, an element like

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

would appear as

@XmlRestrictions(maxLength = 20)
protected String text;

in the generated class file. Then, you could use reflection to extract the restriction information from the field.

The documentation for creating a plugin isn't too great, but I found this article useful. Take a look at the source code for the Default Value Plugin to see how to drill down into XJC's in-memory representation of the XML schema and generated class structure. The JAXB, XSOM, and CodeModel API's will also be helpful.


Looks like the XSD contains semantic "guidelines" instead of clear rules. IMHO if an XSD is agreed upon, not complying to it results in a violation.

If this is not the case and the XSD contains guidelines that are subject to interpretation I would invest time in understanding XSD parsing APIs and try to solve the problem that way. No use in reinventing wheels here.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜