tags:

views:

248

answers:

1

Geven XML file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ExternalRequestContext [
<!ELEMENT ExternalRequestContext EMPTY>
<!ATTLIST ExternalRequestContext
 requestType CDATA #REQUIRED
 deepEnrichment (true | false) "false"
 channelMandatory (true | false) "true">
]
>

<ExternalRequestContext requestType="News" deepEnrichment="false" />

And xStream code

@XStreamAlias("ExternalRequestContext")
class ERC {
 private String requestType;
 private boolean deepEnrichment;
 private boolean channelMandatory;
}
...
XStream x = new XStream();
x.processAnnotations(ERC.class);
ERC erc = (ERC)x.fromXML(new FileReader("C:/Projects/Forwarder/Test.xml"));
x.toXML(erc, System.out);

My browser renders it as following:

<ExternalRequestContext requestType="News" deepEnrichment="false" channelMandatory="true" />

Note that channelMandatory="true" (browser processed the DTD instruction)

while xStream produces

<ExternalRequestContext>
  <deepEnrichment>false</deepEnrichment>
  <channelMandatory>false</channelMandatory>
</ExternalRequestContext>

Here channelMandatory="false" (xStream ignored the "channelMandatory (true | false) "true"" DTD instruction)

What do I miss? How to "tell" xStream to process DTD instructions? And how do I enable DTD validation in xStream?

A: 

This could be because you're using the primitive boolean type. When class ERC is instantiated, the channelMandatory field is initialized by java to false. Since the document contains no data for that field, it stays at false.

DTD validation in java is just that - validation. It doesn't modify the document, it leaves it as it was, it just permits channelMandatory to be not present, knowing that it has a default value. If a web browser chooses to do other wise, that's fine, but that's going beyond validation.

You could try the simplest potential solution - initialise the channelMandatory field to true, e.g.

@XStreamAlias("ExternalRequestContext")
class ERC {
 private String requestType;
 private boolean deepEnrichment = false;
 private boolean channelMandatory = true;
}

That would probably work fine. This is the approach that JAXB takes for generating a java object model from a schema, I think.

skaffman
Fine! Using a wrapper class instead of primitive type can indicate whether a value was given in the XML file.Explicit initialization, however, didn't work: I get channelMandatory is false regardless its initial value.Regarding to validation: can I make xStream to throw an exception if I feed it with invalid (but well-formed) XML?
Lopotun