修复print语句的格式

时间:2014-07-16 17:13:01

标签: java xml eclipse string printing

我最近刚开始使用文档构建器来使用我的XML构建标题。这是我现在使用的以下代码:

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    InputStream inputStream = new FileInputStream(new File("c:\\staff.xml"));
    org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
    StringWriter stw = new StringWriter();       
    Transformer serializer = TransformerFactory.newInstance().newTransformer();
    serializer.transform(new DOMSource(doc), new StreamResult(stw));
    String xmldata = (stw.toString());
    System.out.println(xmldata);

它可以很好地构建标题,但由于解析,它开始在同一行上编写XML文件。有人可以告诉我如何更改此代码以将<company>放到第二行吗? 这是我的印刷品:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><company>
    <comp id="512">
        <firstname>Brandon</firstname>
        <lastname>Liens</lastname>
        <empid>612</empid>
        <rqid>51265</rqid>
    </comp>
</company>

Staff.XML文件:

<company>
    <comp id="512">
        <firstname>Brandon</firstname>
        <lastname>Nyberg</lastname>
        <empid>612</empid>
        <rqid>51265</rqid>
    </comp>
</company>

1 个答案:

答案 0 :(得分:0)

您无法在XML声明后自动添加换行符,但如果您可以完全删除XML声明,则可以在Transformer serializer = ...行之后添加此行:

serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");