我的代码使用 LSSerializer 类编写一个 XML 文件:
DOMImplementation impl = doc.getImplementation();
DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS","3.0");
LSSerializer ser = implLS.createLSSerializer();
String str = ser.writeToString(doc);
System.out.println(str);
String file = racine+"/"+p.getNom()+".xml";
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
out.write(str);
out.close();
XML 格式正确,但在解析它时出现错误。
解析代码:
File f = new File(racine+"/"+filename);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
XPathFactory xpfactory = XPathFactory.newInstance();
XPath xp = xpfactory.newXPath();
String expression;
expression = "root/nom";
String nom = xp.evaluate(expression, doc);
错误:
[Fatal Error] Terray.xml:1:40: Content is not allowed in prolog.
9 août 2011 19:42:58 controller.MakaluController activatePatient
GRAVE: null
org.xml.sax.SAXParseException: Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:249)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:208)
at model.MakaluModel.setPatientActif(MakaluModel.java:147)
at controller.MakaluController.activatePatient(MakaluController.java:59)
at view.ListePatientsPanel.jButtonOKActionPerformed(ListePatientsPanel.java:92)
...
现在,通过一些研究,I found这个错误是由于 XML 开头的“隐藏”字符造成的。
事实上,我可以通过手动创建 XML 文件来修复错误。
但是XML写错在哪里呢? (当我尝试打印字符串时,ths 之前没有空格
解决方案:更改序列化器
我运行了一段时间UTF-16编码的方案,但不是很稳定。 所以我找到了一个新的解决方案:更改 XML 文档的序列化程序,使 XML header 和文件编码之间的编码保持一致。 :
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
String file = racine+"/"+p.getNom()+".xml";
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
transformer.transform(domSource, new StreamResult(out));
最佳答案
But where is the error in the XML writing ?
看起来错误不在写作中,而是在解析中。正如您已经发现的,文件开头有一个空白字符,这会导致您的 stach 跟踪中的解析调用出错:
Document doc = builder.parse(f);
打印出来时看不到空格的原因可能只是您使用的编码。尝试更改此行:
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
使用“UTF-16”或“US-ASCII”
关于Java XML 解析错误 : Content is not allowed in prolog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7000640/