Adding XML Style-Sheet at specific line of XML Document in JAVA

Last days I was searching for adding XML style sheet at specific line of XML document using JAVA and I found the solution. Therefore want to share here for audience convenience.

Here are the steps how do it.
  • Converting XML document to String
  • Adding Style-Sheet at second line
  • Converting String back to XML file
Here is the main method which is the calling entry point of my main business logic:

public static void main(String[] args) throws TransformerConfigurationException 
{
             
  final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
                       +"<Emp id=\"1\"><name>naeemgik.blogspot.com</name><age>25</age>\n"
                       + "<role>Developer</role><gen>Male</gen></Emp>";
  Document beforeAddingStyleSheetDocument = convertStringToDocument(xmlStr);
             
  Document afterAddingStyleSheetDocument = null;
              
 try {
      afterAddingStyleSheetDocument = addingStylesheet(beforeAddingStyleSheetDocument);
 } catch (ParserConfigurationException e) {
     e.printStackTrace();
 }
             
 String stringAfterAddingStylesheet = convertDocumentToString(afterAddingStyleSheetDocument);
 System.out.println(stringAfterAddingStylesheet);
}



Code snippet for converting XML String to Document


private static Document convertStringToDocument(String xmlStr)

{

       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

       DocumentBuilder builder;

       Document doc = null;
       try {
              builder = factory.newDocumentBuilder();
              doc = builder.parse(new InputSource(new StringReader(xmlStr)));

       } catch (Exception e) {
              e.printStackTrace();
       }
       return doc;
}  



Now adding style-sheet at corresponding line (e.g. here at second line) of XML document

private static <ProcessingInstructionImpl> Document addingStylesheet(

                     Document doc) throws TransformerConfigurationException,

                     ParserConfigurationException

{
       ProcessingInstructionImpl pi = (ProcessingInstructionImpl) doc
                           .createProcessingInstruction("xml-stylesheet",
                                         "type=\"text/xsl\" href=\"CDA.xsl\"");
       Element root = doc.getDocumentElement();
       doc.insertBefore((Node) pi, root);

       return doc;

}

Converting String text back to XML document


private static String convertDocumentToString(Document doc)

 {

        TransformerFactory tf = TransformerFactory.newInstance();

        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            // below code to remove XML declaration
        // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
        // "yes");
        StringWriter writer = new StringWriter();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString();
            return output;
        } catch (TransformerException e) {
            e.printStackTrace();
        }

 }


               ~~~~~~~~~~~~~ So enjoy thats all ~~~~~~~~~~~~~~~~~~~~

No comments:

Post a Comment