2

I have xml string file in which I want to add xml-stylesheet at the seconed line of xml string file. but the code given below give me the output like this: first the xml- string file and then append xml-stylesheet at the end of xml string file but I want the style-sheet at the seconed line of my xml-string.please suggest me how should I do this. thanks.

my code is:

public class StringToDocumentToString {

public static void main(String[] args)
        throws TransformerConfigurationException {
    String xmlstring = null;
    String filepath = "E:/C-CDA/MU2_CDA_WORKSPACE/AddingStylesheetTOxml/documentfile.txt";
    final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"
            + "<role>Developer</role><gen>Male</gen></Emp>";


    Document doc2 = convertStringToDocument(xmlStr);
    Document doc1 = null;
    try {
        doc1 = addingStylesheet(doc2);
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String str = convertDocumentToString(doc1);
    System.out.println(str);
}

private static <ProcessingInstructionImpl> Document addingStylesheet(
        Document doc) throws TransformerConfigurationException,
        ParserConfigurationException {

    ProcessingInstructionImpl pi = (ProcessingInstructionImpl) doc
            .createProcessingInstruction("xml-stylesheet",
                    "type=\"text/xsl\" href=\"my.stylesheet.xsl\"");
    Element root = doc.createElement("root-element");
    doc.appendChild(root);

    doc.insertBefore((Node) pi, root);
    return doc;

}

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.transform(new DOMSource(doc), new StreamResult(writer));
        String output = writer.getBuffer().toString();
        return output;
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    return null;
}

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;
}
}

1 Answer 1

1

The statement Element root = doc.createElement("root-element"); creates a new element named root-element and when you call doc.appendChild(root); you're actually appending it to the end of the document. So after these two statement, your document would be something like this:

<?xml version="1.0" encoding="UTF-8"?>
<Emp id="1">
    <name>Pankaj</name>
    <age>25</age>
    <role>Developer</role>
    <gen>Male</gen>
</Emp>
<root-element/>

Then you have doc.insertBefore((Node) pi, root); which causes to add the stylesheet processing instruction just before this newly added element.

To fix this, you have to retrieve a pointer to your document root element (instead of adding a new element named root-element) and then add the pi just before it. This would be possible by calling getDocumentElement() method of the doc object. So in order to fix the problem you just need to use the following code in your main method:

Element root = doc.getDocumentElement();
doc.insertBefore((Node) pi, root);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.