Anu*_*rag 7 java xml encoding stax
我使用StAX创建XML文件,然后使用和XSD验证文件.
我在创建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)
Run Code Online (Sandbox Code Playgroud)
这是代码片段:
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();
}
Run Code Online (Sandbox Code Playgroud)
我在Unix上运行这段代码.有谁知道如何设置版本和编码样式?
Phi*_*Lho 14
我也会尝试使用createXMLStreamWriter()
带输出参数.
[编辑]尝试,它通过更改createXMLStreamWriter行来工作:
XMLStreamWriter xtw = xof.createXMLStreamWriter(new FileOutputStream(fileName), "UTF-8");
Run Code Online (Sandbox Code Playgroud)
[编辑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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这应该工作:
// ...
Writer writer = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
XMLStreamWriter xtw = xof.createXMLStreamWriter(writer);
xtw.writeStartDocument("UTF-8", "1.0");
// ...
Run Code Online (Sandbox Code Playgroud)