简体   繁体   中英

JAXB issue with missing namespace definition

So I searched around quite a bit for a solution to this particular issue and I am hoping someone can point me in a good direction.

We are receiving data as XML, and we only have XSD to validate the data. So I used JAXB to generate the Java classes. When I went to unmarshal a sample XML, I found that some attribute values are missing. It turns out that the schema expects those attributes to be QName, but the data provider didn't define the prefix in the XML.

For instance, one XML attribute value is "repository:<uuid>" , but the namespace prefix "repository" is never defined in the dataset. (Never mind the provider's best practices suggest defining it!)

So when I went to unmarshal a sample set, the QName attributes with the specified prefix ("repository" in my sample above) are NULL! So it looks like JAXB is "throwing out" those attribute QName values which have undefined namespace prefix. I am surprised that it doesn't preserve even the local name.

Ideally, I would like to maintain the value as is, but it looks like I can't map the QName to a String at binding time (Schema to Java).

I tried "manually" inserting a namespace definition to the XML and it works like a charm. What would be the least complicated method to do this?

Is there a way to "insert" namespace mapping/definition at runtime? Or define it "globally" at binding time?

The simplest would be to use strings instead of QName. You can use the javaType customization to achieve this .

If you want to add prefix/namespace mappings in the runtime, there are quite a few ways to do it:

  • Similar to above, you could provide your own QName converter which would consider your prefixes.
  • You can put a SAX or StAX filter in between and declare additional prefixes in the startDocument .
  • What you actually need is to add your prefix mappings into the UnmarshallingContext.environmentNamespaceContext . I've checked the source code but could not find a direct and easy way to do it.

I personally would implement a SAX/StAX filter to "preprocess" your XML on the event level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM