Java 使用XML架构创建XML文件:格式错误的DbyteSequenceException
我想使用JAXB创建具有指定XML模式文件的XML文档。当我在Eclipse中运行我的应用程序时,它运行得很好。后来我构建了runnable jar。应用程序运行良好,但当我尝试保存文件时,出现了一个错误,这在Eclipse中不存在: 格式错误的字节序列异常:4字节UTF-8序列的字节2无效 有几个职能部门负责整个过程:Java 使用XML架构创建XML文件:格式错误的DbyteSequenceException,java,xml,jaxb,Java,Xml,Jaxb,我想使用JAXB创建具有指定XML模式文件的XML文档。当我在Eclipse中运行我的应用程序时,它运行得很好。后来我构建了runnable jar。应用程序运行良好,但当我尝试保存文件时,出现了一个错误,这在Eclipse中不存在: 格式错误的字节序列异常:4字节UTF-8序列的字节2无效 有几个职能部门负责整个过程: private String generateXML() throws JAXBException, BladWalidacjiXml { JAXBContext ja
private String generateXML() throws JAXBException, BladWalidacjiXml {
JAXBContext jaxbContext = JAXBContext
.newInstance(RootClass.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter xmlDocument = new StringWriter();
jaxbMarshaller.marshal(rootClass, xmlDocument);
String xml = xmlDocument.toString();
try {
XmlParser.validateWithXSD(xml);
} catch (SAXException e) {
throw new BladWalidacjiXml(e);
} catch (IOException e) {
throw new BladWalidacjiXml(e);
}
return xml;
}
public static void validateWithXSD(String xml) throws SAXException, IOException {
validate(new StreamSource(new ByteArrayInputStream(xml.getBytes())));
}
private static boolean validate(StreamSource xmlFile) throws SAXException, IOException{
File schemaFile = new File(SCHEMA_FILE_PATH);
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
javax.xml.validation.Validator validator = schema.newValidator();
validator.validate(xmlFile);
return true;
}
XML中的节点可能包括波兰国家符号,如ą、ę、ź等。我想这不是错误的原因,但可能我错了
如果有任何帮助,我将不胜感激
编辑:
创建XML文件的代码:
public void saveToFile() throws JAXBException, IOException,
BladWalidacjiXml {
PrintWriter ostream = null;
boolean deleteFile = false;
try {
ostream = new PrintWriter("file.xml", "UTF-8");
ostream.write(generateXML());
} catch (JAXBException e) {
deleteFile = true;
throw e;
} catch (IOException e) {
deleteFile = true;
throw e;
} catch (BladWalidacjiXml e) {
deleteFile = true;
throw e;
} finally {
if (ostream != null) {
ostream.close();
}
}
}
您可以发布创建xml文件的代码吗?当然,我已经更新了我的帖子。我发现解决方案-必须在validateWithXSD函数中设置编码,如下所示:xml.getBytesUTF-8;