Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Node to String in Java

Tags:

java

xml

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 = 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(); } 

It looks straightforward in that it wants the output string doesn't have any XML declaration and it must contain indentation.

But I wonder how the actual output should be, suppose I have an XML node:

<p><media type="audio" id="au008093" rights="wbowned"> <title>Bee buzz</title> </media>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.</p> 

Could I assume the resulting String after applying the above transformation is:

"media type="audio" id="au008093" rights="wbowned" title Bee buzz title /media" 

I want to test it myself, but I have no idea on how to represent this XML node in the way this function actually wants.

I am bit confused, and thanks in advance for the generous help.

like image 296
Kevin Avatar asked Dec 10 '10 20:12

Kevin


People also ask

Can we convert XML to string in Java?

1.1) Print XML to Console or Log File //A character stream that collects its output in a string buffer, //which can then be used to construct a string.

How do I read an XML string in Java?

You can parse the XML file using XPath expression, you can do XSL transformation, XSD schema validation and you can even parse whole XML file as String in just a couple of lines of code.

How do I convert something to a string in Java?

Convert Object to String in java using toString() method of Object class or String. valueOf(object) method. Since there are mainly two types of class in java, i.e. user-defined class and predefined class such as StringBuilder or StringBuffer of whose objects can be converted into the string.


1 Answers

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 =        "<p>" +       "  <media type=\"audio\" id=\"au008093\" rights=\"wbowned\">" +       "    <title>Bee buzz</title>" +       "  " +       "  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." +       "</p>";     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:

  <p>  <media id="au008093" rights="wbowned" type="audio">    <title>Bee buzz</title>  </media>  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.</p>  

You can further tweak it by yourself. Good luck!

like image 165
Jiri Patera Avatar answered Sep 23 '22 09:09

Jiri Patera