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; 
        }
                Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty("omit-xml-declaration", "yes");
serializer.transform(new DOMSource(doc), new StreamResult(stw));
Good and old XSL ;).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With