简体   繁体   English

为什么XMLStreamReader / StAXSource会从XML中删除注释?

[英]Why does XMLStreamReader/StAXSource strip comments from XML?

The code below (based on sample code from http://jax-ws.java.net/nonav/jax-ws-20-fcs/arch/com/sun/xml/ws/util/xml/StAXSource.html ) 下面的代码(基于http://jax-ws.java.net/nonav/jax-ws-20-fcs/arch/com/sun/xml/ws/util/xml/StAXSource.html中的示例代码)

String xml = "<a><b>a text</b><!--a comment--><b/></a>";
StringReader sr = new StringReader(xml);
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(sr);
Source source = new StAXSource(reader);     
//Source source = new StreamSource(sr);
Result result = new StreamResult(System.out);      
TransformerFactory.newInstance().newTransformer().transform(source, result);

yields the following result: 得到以下结果:

<?xml version="1.0" encoding="UTF-8"?><a><b>a text</b><b/></a>

ie it strips out the xml comment. 即它删除了xml注释。 If I replace the StAXSource/XMLStreamReader with the StreamSource the comment is preserved. 如果我用StreamSource替换StAXSource / XMLStreamReader,则保留注释。

Does anyone know why the XMLStreamReader/StAXSource combination strips them out and if there is any way to prevent it? 有谁知道为什么XMLStreamReader / StAXSource组合剥离它们,如果有任何方法可以阻止它? The testing was done in 1.6 and 1.7 environments with no third party jars, so the XMLStreamReader becomes a 测试是在没有第三方jar的1.6和1.7环境中完成的,因此XMLStreamReader成为了一个

com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl 

Thanks 谢谢

EDIT: Just tried as described here ie 编辑:只是试图描述这里

case XMLStreamConstants.COMMENT:
  System.out.print("<!--");
  if (xmlr.hasText())
     System.out.print(xmlr.getText());
...

and it DOES read the comments. 并且它已阅读评论。 This does not answer the original question yet though ... 尽管如此,这还不能回答原来的问题......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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