我有一个 xml 字符串代码。这个字符串可以是格式正确的,也可以不是格式正确的,我应该返回一个格式正确的 xml 字符串。
我使用了这段代码,它工作得很好:
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);
}
}
但我发现了一个带有这个声明的 xml 字符串的错误:
<?xml version=
1.0 编码= utf-8 ?>
这是给定的错误:
org.xml.sax.SAXParseException:XML 声明中“版本”后面的值必须是带引号的字符串。
我也试过这段代码,但我得到了同样的错误:
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
}
}
你有什么想法我可以解决它吗?可能不删除原始声明。
谢谢!!