开发者

Default value from DTD in xStream

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:

<Externa开发者_运维问答lRequestContext 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?


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜