Java StAX - 使用 XMLStreamWriter 设置版本和编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2943605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
StAX - Setting the version and encoding using XMLStreamWriter
提问by Anurag
I am using StAX for creating XML files and then validating the file with and XSD.
我使用 StAX 创建 XML 文件,然后使用 XSD 验证文件。
I am getting an error while creating the XML file:
创建 XML 文件时出现错误:
javax.xml.stream.XMLStreamException: Underlying stream encoding 'Cp1252' and input paramter for writeStartDocument() method 'UTF-8' do not match.
at com.sun.xml.internal.stream.writers.XMLStreamWriterImpl.writeStartDocument(XMLStreamWriterImpl.java:1182)
Here is the code snippet:
这是代码片段:
XMLOutputFactory xof = XMLOutputFactory.newInstance();
try{
XMLStreamWriter xtw = xof.createXMLStreamWriter(new FileWriter(fileName));
xtw.writeStartDocument("UTF-8","1.0");} catch(XMLStreamException e) {
e.printStackTrace();
} catch(IOException ie) {
ie.printStackTrace();
}
I am running this code on Unix. Does anybody know how to set the version and encoding style?
我在 Unix 上运行此代码。有人知道如何设置版本和编码风格吗?
回答by PhiLho
I would try to use the createXMLStreamWriter()
with an output parameter too.
我也会尝试将createXMLStreamWriter()
与输出参数一起使用。
[EDIT] Tried, it works by changing the createXMLStreamWriter line:
[编辑] 尝试过,它通过更改 createXMLStreamWriter 行来工作:
XMLStreamWriter xtw = xof.createXMLStreamWriter(new FileOutputStream(fileName), "UTF-8");
[EDIT 2] Made a little more complex test, for the record:
[编辑 2] 做了一个更复杂的测试,以供记录:
String fileName = "Test.xml";
XMLOutputFactory xof = XMLOutputFactory.newInstance();
XMLStreamWriter xtw = null;
try
{
xtw = xof.createXMLStreamWriter(new FileOutputStream(fileName), "UTF-8");
xtw.writeStartDocument("UTF-8", "1.0");
xtw.writeStartElement("root");
xtw.writeComment("This is an attempt to create an XML file with StAX");
xtw.writeStartElement("foo");
xtw.writeAttribute("order", "1");
xtw.writeStartElement("meuh");
xtw.writeAttribute("active", "true");
xtw.writeCharacters("The cows are flying high this Spring");
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeStartElement("bar");
xtw.writeAttribute("order", "2");
xtw.writeStartElement("tcho");
xtw.writeAttribute("kola", "K");
xtw.writeCharacters("Content of tcho tag");
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeEndDocument();
}
catch (XMLStreamException e)
{
e.printStackTrace();
}
catch (IOException ie)
{
ie.printStackTrace();
}
finally
{
if (xtw != null)
{
try
{
xtw.close();
}
catch (XMLStreamException e)
{
e.printStackTrace();
}
}
}
回答by chris
This should work:
这应该有效:
// ...
Writer writer = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
XMLStreamWriter xtw = xof.createXMLStreamWriter(writer);
xtw.writeStartDocument("UTF-8", "1.0");
// ...
回答by StaxMan
From the code it is hard to know for sure, but if you are relying on the default Stax implementation that JDK 1.6 provides (Sun sjsxp) I would recommend upgrading to use Woodstox. It is known to be less buggy than Sjsxp, supports the whole Stax2 API and has been actively developed and supported (whereas Sun version was just written and there has been limited number of bug fixes).
从代码中很难确定,但如果您依赖 JDK 1.6 提供的默认 Stax 实现(Sun sjsxp),我建议升级以使用Woodstox。众所周知,它比 Sjsxp 的 bug 少,支持整个 Stax2 API,并且得到了积极的开发和支持(而 Sun 版本刚刚编写,错误修复数量有限)。
But the bug in your code is this:
但是您代码中的错误是这样的:
XMLStreamWriter xtw = xof.createXMLStreamWriter(new FileWriter(fileName));
you are relying on the default platform encoding (which must be CP-1252, windows?). You should always explicitly specify encoding you are using. Stream writer is just verifying that you are not doing something dangerous, and spotted inconsistence that can cause corrupt document. Pretty smart, which actually suggests that this is not the default Stax processor. :-)
您依赖于默认平台编码(必须是 CP-1252,Windows?)。您应该始终明确指定您正在使用的编码。Stream writer 只是验证您没有做一些危险的事情,并发现可能导致损坏文档的不一致。非常聪明,这实际上表明这不是默认的 Stax 处理器。:-)
(the other answer points a correct workaround, too, by just passing OutputStream and encoding to let XMLStreamWriter do the right thing)
(另一个答案也指出了正确的解决方法,只需传递 OutputStream 和 encoding 即可让 XMLStreamWriter 做正确的事情)
回答by rmuller
If using the default XMLStreamWriter
bundled with the Oracle JRE/JDK you should always
如果使用XMLStreamWriter
与 Oracle JRE/JDK 捆绑的默认值,您应该始终
- create a
XMLStreamWriter
, explicitly setting the character encoding:xmlOutputFactory.createXMLStreamWriter(in, encoding)
- start the document and explicitly setting the encoding:
xmlStreamWriter.writeStartDocument(encoding, version)
. The writer is not smart enough remembering the encoding set when the writer was created. However, it checks if these encodings are the same. See code below.
- 创建一个
XMLStreamWriter
,明确设置字符编码:xmlOutputFactory.createXMLStreamWriter(in, encoding)
- 启动文档并显式设置编码:
xmlStreamWriter.writeStartDocument(encoding, version)
. 编写器在创建编写器时记住编码集不够聪明。但是,它会检查这些编码是否相同。请参阅下面的代码。
This way, your file encoding and XML declaration are always in sync. Although specifying the encoding in the XML declaration is optional, XML best practice is to always specify it.
这样,您的文件编码和 XML 声明将始终保持同步。尽管在 XML 声明中指定编码是可选的,但 XML 最佳实践是始终指定它。
This is the code from the Oracle (Sun) implementation (Sjsxp):
这是来自 Oracle (Sun) 实现 (Sjsxp) 的代码:
String streamEncoding = null;
if (fWriter instanceof OutputStreamWriter) {
streamEncoding = ((OutputStreamWriter) fWriter).getEncoding();
}
else if (fWriter instanceof UTF8OutputStreamWriter) {
streamEncoding = ((UTF8OutputStreamWriter) fWriter).getEncoding();
}
else if (fWriter instanceof XMLWriter) {
streamEncoding = ((OutputStreamWriter) ((XMLWriter)fWriter).getWriter()).getEncoding();
}
if (streamEncoding != null && !streamEncoding.equalsIgnoreCase(encoding)) {
// If the equality check failed, check for charset encoding aliases
boolean foundAlias = false;
Set aliases = Charset.forName(encoding).aliases();
for (Iterator it = aliases.iterator(); !foundAlias && it.hasNext(); ) {
if (streamEncoding.equalsIgnoreCase((String) it.next())) {
foundAlias = true;
}
}
// If no alias matches the encoding name, then report error
if (!foundAlias) {
throw new XMLStreamException("Underlying stream encoding '"
+ streamEncoding
+ "' and input paramter for writeStartDocument() method '"
+ encoding + "' do not match.");
}
}