gpt4 book ai didi

java - StAX - 使用 XMLStreamWriter 设置版本和编码

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:02:17 26 4
gpt4 key购买 nike

我使用 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)

这是代码片段:

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();

}

我在 Unix 上运行这段代码。有人知道如何设置版本和编码风格吗?

最佳答案

我也会尝试使用带有输出参数的 createXMLStreamWriter()

[编辑] 尝试过,它通过更改 createXMLStreamWriter 行来工作:

XMLStreamWriter xtw = xof.createXMLStreamWriter(new FileOutputStream(fileName), "UTF-8");

[EDIT 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();
}
}
}

关于java - StAX - 使用 XMLStreamWriter 设置版本和编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2943605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com