xstream is converting & to & when converting from xml to Java Objects

亡梦爱人 提交于 2020-01-07 02:18:53

问题


xstream is converting & to & when converting from xml to Java Objects. I don't want this to happen. How shall I do it?

 XStream xstream = new XStream(new DomDriver());

            xstream.processAnnotations(HelpConfigVO.class);
            xstream.processAnnotations(ProductVO.class);
            xstream.processAnnotations(PackageVO.class);
            xstream.addImplicitCollection(HelpConfigVO.class, "packages");
            configVO = (HelpConfigVO)xstream.fromXML(helpConfigData);

Secondly, The output XML I am getting from xstream is not formatted. How do I format my xml to make it readable?


回答1:


xstream is converting "&" to "&" when converting from xml to Java Objects.

As it should. It would be broken if it didn't

I don't want this to happen.

Why? The "&" in the XML means "&".

How shall I do it?

No valid XML parser will do this for you because it is an egregious violation of the XML spec. In theory, you could hack an open source XML parser to do this abominable act ... but I'd strongly advise against it.


If correct behavior in the parser is causing you problems, you've got a flaw in your application design. You should do something like:

  • not parsing the XML - store it as character sequence, OR

  • reinsert the character entities by applying the XML escape mapping to the text before you use it.




回答2:


The website for the software says "XStream is a simple library to serialize objects to XML and back again". Since & is XML for & it wouldn't make sense for it not to convert it, and I doubt very much it has a "Convert to text except for ampersands which would continue to be XML" feature.

It sounds like you have an XY problem. Why do you want & in the data?

Assuming that it is because you are outputting XML or HTML, the appropriate solution is to treat the text as text and either:

  • Use the "insert text" feature of whatever library you are using to build the XML/HTML (as opposed to the "insert markup" feature)
  • Run the text though an escaping function (such as Perl's HTML::Entities module or PHP's htmlspecialchars function (I don't use Java enough to recommend one for that language, but the principle is the same)).



回答3:


You can't. & means ampersant; it's correct for xstream to do this. If you really want the output to be "&", you need && in your code, or put it inside a CDATA section.




回答4:


&is a XML entity.

See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML

It makes sense that XStream unescapes it to & for a Java String.



来源:https://stackoverflow.com/questions/8941911/xstream-is-converting-amp-to-when-converting-from-xml-to-java-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!