I'm trying to convert a XML org.w3c.dom.Document to a String using a 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);
I'm using my objects called Game and Score, which shouldn't interfere with the process.
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";
}
}
For some reason the transformer.transform method does not complete successfully.
Here is Document converter which works fine for me