XML Node to String in Java

前端 未结 2 977
栀梦
栀梦 2020-11-30 11:13

I came across this piece of Java function to convert an XML node to a Java String representation:

private String nodeToString(Node node) {
StringWriter sw =          


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 11:22

    All important has already been said. I tried to compile the following code.

    
    import java.io.ByteArrayInputStream;
    import java.io.InputStream;
    import java.io.StringWriter;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    
    public class Test {
    
      public static void main(String[] args) throws Exception {
    
        String s = 
          "

    " + " " + " Bee buzz" + " " + " Most other kinds of bees live alone instead of in a colony." + " These bees make tunnels in wood or in the ground." + " The queen makes her own nest." + "

    "; InputStream is = new ByteArrayInputStream(s.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.parse(is); Node rootElement = d.getDocumentElement(); System.out.println(nodeToString(rootElement)); } private static String nodeToString(Node node) { StringWriter sw = new StringWriter(); try { Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(new DOMSource(node), new StreamResult(sw)); } catch (TransformerException te) { System.out.println("nodeToString Transformer Exception"); } return sw.toString(); } }

    And it produced the following output:

    
    

    Bee buzz Most other kinds of bees live alone instead of in a colony. These bees make tunnels in wood or in the ground. The queen makes her own nest.

    You can further tweak it by yourself. Good luck!

提交回复
热议问题