转换org.w3c.dom.使用Transformer将Java文档转换为字符串



我正在尝试转换XML org.w3c.dom。使用Transformer将文档转换为字符串:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document doc = builder.newDocument();
    Element gameNode = doc.createElement("Game");
    gameNode.setAttribute("gameID", String.valueOf(game.getGameID()));
    gameNode.setAttribute("username", game.getUsername());
    gameNode.setAttribute("gameStartTime", String.valueOf(game.getGameStartTime()));
    gameNode.setAttribute("gameStartDate", String.valueOf(game.getGameStartDate()));
    gameNode.setAttribute("totalScore", String.valueOf(game.getTotalScore()));
    gameNode.setAttribute("totalTimeInSeconds", String.valueOf(game.getTotalTimeInSeconds()));
    gameNode.setAttribute("lastLevel", String.valueOf(game.getLastLevel()));
    gameNode.setAttribute("firstLevel", String.valueOf(game.getFirstLevel()));
    doc.appendChild(gameNode);

    for(int i = 0 ; i < game.getScores().size(); i++)
    {
        Element scoreNode = doc.createElement("Score");
        scoreNode.setAttribute("gameID", String.valueOf(game.getScores().get(i).getGameID()));
        scoreNode.setAttribute("points", String.valueOf(game.getScores().get(i).getPoints()));
        scoreNode.setAttribute("levelOfScore", String.valueOf(game.getScores().get(i).getLevelOfScore()));
        scoreNode.setAttribute("timeToScore", String.valueOf(game.getScores().get(i).getTimeToScore()));
        gameNode.appendChild(scoreNode);
    }

    return DocumentToString(doc);

我正在使用我的对象Game和Score,它们不应该干扰这个过程。

public static String DocumentToString(Document doc)
{
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(System.out);  
        transformer.transform(source, result); 
        return "yeah";
    } catch (Exception ex) {
        return "Error converting to String";
    }
}

由于某种原因,变压器。转换方法未成功完成。

这是一个适合我的文档转换器

public String getStringFromDoc(Document doc) throws TransformerException {
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(domSource, result);
        writer.flush();
        return writer.toString();
    }

相关内容

  • 没有找到相关文章

最新更新