Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing XML in Java without the xml file tag

Tags:

java

xml

Is there a way to print the XML content without the XML header tag in Java?

For example if I have an XML like this:

<?xml version='1.0' encoding='UTF-8'?>
<rootElement>
<childElement>Text</childElement>
</rootElement>

I just want to print

<rootElement>
<childElement>Text</childElement>
</rootElement>

This is very similar to what I am doing so far: http://sacrosanctblood.blogspot.com/2008/07/convert-xml-file-to-xml-string-in-java.html

I cannot give out the exact source code but the above link example should give you some idea. Here's that code with imports:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Text;

public String convertXMLFileToString(String fileName) 
        { 
          try{ 
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 
            InputStream inputStream = new FileInputStream(new File(fileName)); 
            org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream); 
            StringWriter stw = new StringWriter(); 
            Transformer serializer = TransformerFactory.newInstance().newTransformer(); 
            serializer.transform(new DOMSource(doc), new StreamResult(stw)); 
            return stw.toString(); 
          } 
          catch (Exception e) { 
            e.printStackTrace(); 
          } 
            return null; 
        }
like image 685
Ankit Avatar asked Aug 09 '11 01:08

Ankit


1 Answers

Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty("omit-xml-declaration", "yes");
serializer.transform(new DOMSource(doc), new StreamResult(stw));

Good and old XSL ;).

like image 133
Anthony Accioly Avatar answered Nov 12 '22 02:11

Anthony Accioly