如何抑制javax.xml.transform.Transformer的Transformer添加的xml元素
我一直在使用 Java API 来解析 XML 文件,以便添加、删除或更新元素/属性。一切都按照我想要的方式工作,除了我使用的 Transformer
对象添加了 到 XML 文件的开头。我想知道是否有办法抑制这种情况。
PS我还注意到这个投票最高的 answer 提到我们也许能够抑制它。
DOMSource source = new DOMSource(document);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
FileOutputStream fout = new FileOutputStream(new File(outputFile));
StreamResult result = new StreamResult(fout);
transformer.transform(source, result);
fout.close();
原文档不包含
I've been using the Java APIs to parse an XML file so I could add, remove, or update elements/attributes. Everything works the way I want, except that the Transformer
object I'm using adds <?xml version="1.0" encoding="UTF-8"?>
to the beginning of the XML file. I was wondering if there is a way to suppress this.
P.S. I also noticed that this top-voted answer mentioned that we might be able to supress it.
DOMSource source = new DOMSource(document);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
FileOutputStream fout = new FileOutputStream(new File(outputFile));
StreamResult result = new StreamResult(fout);
transformer.transform(source, result);
fout.close();
The original document does not contain <?xml version="1.0" encoding="UTF-8"?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
已接受答案的替代方案。但我觉得这样比较好..
An alternative to the accepted answer. But I think this is better..
如果您可以更改 XSLT,则只需添加
,或者如果样式表中已有
元素,则只需添加omit-xml-declaration =“yes”
属性值。如果您无法更改 XML,则根据特定转换器的序列化程序实现,您也许能够设置参数或功能来禁用 XML 声明。从技术上讲,这是输出串行器的一个选项,而不是变压器本身,并且某些实现允许您将参数传递给串行器。具体如何实现这一点取决于实施情况。
If you can change the XSLT, then just add
or if you already have an
<xsl:output.../>
element in the stylesheet, just add theomit-xml-declaration="yes"
attribute value.If you can't change the XML, then depending on the specific transformer's serializer implementation, you may be able to set a parameter or feature to disable the XML declaration. Technically this is an option to the output serializer, not the transformer per se, and some implementations allow you to pass parameters to the serializer. How you actually accomplish this depends on the implementation.