Convert an org.w3c.dom.Node into a String

前端 未结 3 438
忘掉有多难
忘掉有多难 2020-12-09 15:25

Sorry I\'m a Java/XML newbie - and can\'t seem to figure this one out. It seems it\'s possible to convert a Document object to a string. However, I want to convert a Node ob

3条回答
  •  攒了一身酷
    2020-12-09 15:55

    String getNodeString(Node node) {
        try {
            StringWriter writer = new StringWriter();
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.transform(new DOMSource(node), new StreamResult(writer));
            String output = writer.toString();
            return output.substring(output.indexOf("?>") + 2);//remove 
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return node.getTextContent();
    }
    

提交回复
热议问题