Java pretty print XML version=1.0 with no quote

trancedance

New Member
I've a xml string code. This string could be well formatted or not, and I should return a well format xml string.I used this code and it was working great:\[code\]try { final Document document = parseXmlFile(code); OutputFormat format = new OutputFormat(document); format.setLineWidth(65); format.setIndenting(true); format.setIndent(2); Writer out = new StringWriter(); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(document); newcode = out.toString(); } catch (IOException e) { throw new RuntimeException(e); }private Document parseXmlFile(String in) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(in)); return db.parse(is); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); }}\[/code\]but I found a bug for xml string with this declaration: \[quote\]\[code\]<?xml version=\[/code\] 1.0 encoding= utf-8 ?>\[/quote\]Here is the given error:org.xml.sax.SAXParseException: The value following "version" in the XML declaration must be a quoted string.I tried also with this code, but i got the same error:\[code\]private static String prettyFormat(String input, int indent) { try { Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Exception e) { throw new RuntimeException(e); // simple exception handling, please review it }}\[/code\]Have you got any ideas how I could fix it? Possibly without removing the original declaration.Thanks!!
 
Back
Top