Java pretty print XML version = 1.0,没有引用

时间:2013-03-17 15:32:23

标签: java xml serialization declaration quote

我有一个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   ?&GT;

以下是给定的错误:

org.xml.sax.SAXParseException:XML声明中“version”后面的值必须是带引号的字符串。

我也试过这段代码,但是我得到了同样的错误:

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
    }
}

你有什么想法我可以解决它吗?可能没有删除原始声明。

谢谢!

0 个答案:

没有答案