2013-10-08 55 views
1

如何在xml文件的第二行添加樣式表,我寫了代碼,但它在我的xml字符串文件的第一行添加了樣式表請看看我的代碼,這是工作的代碼,但它在XML字符串的第一行添加樣式表和我的需求量的是在XML字符串的第二行添加xml樣式表的請幫忙在xml字符串的第二行添加xml樣式表

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=\"cda.xsl\""); 
     Element root = doc.getDocumentElement(); 
     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

轉化

之前
transformer.transform(new DOMSource(doc), new StreamResult(writer)); 

請嘗試以下輸出屬性,

transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); 
+0

感謝您的回答,我已經做出了您建議的更改,並且我的代碼給了我預期的結果。謝謝 –

+0

歡迎!很高興你得到了結果。 – noboundaries