2015-06-23 51 views
0

我有一個未格式化的XML文件(只有一行),我想縮進它:XML縮進和沒有獨立

我的文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><test>toto</test></Document> 

我的Java代碼:

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileWriter; 
import java.io.PrintWriter; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.transform.OutputKeys; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

import org.w3c.dom.Document; 


public class PrettyXmlFormat { 

    public static void main(String[] args) throws Exception { 
     if(args != null && args.length > 0 && args[0].length() > 0) 
     { 
      String FileInputName = "TEST.xml";//"args[0];" 
      runFormat(FileInputName,true); 
     } 
    } 

     public static void runFormat(String FileInputName, boolean standelone) throws Exception { 


       String FileOutputName = FileInputName + "MOD"; 
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
       DocumentBuilder db = dbf.newDocumentBuilder(); 
       Document doc = db.parse(new FileInputStream(new File(FileInputName))); 
       doc.setXmlStandalone(standelone); 
       prettyPrint(doc,FileOutputName); 
     } 

     public static final void prettyPrint(Document xml , String FileOutputName) throws Exception { 
      Transformer tf = TransformerFactory.newInstance().newTransformer(); 
      tf.setOutputProperty(OutputKeys.INDENT, "yes"); 
      PrintWriter FileOut = new PrintWriter(new FileWriter(FileOutputName)); 
      tf.transform(new DOMSource(xml), new StreamResult(FileOut)); 
     } 

} 

我試圖玩doc.setXmlStandalone(standelone);

隨着doc.setXmlStandalone(真),我有這樣的結果:

<?xml version="1.0" encoding="UTF-8"?><Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<test>toto</test> 
</Document> 

隨着doc.setXmlStandalone(假的),我有這樣的結果:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<test>toto</test> 
</Document> 

我想我有獨立的價值產生並在xml聲明之後逃脫:

<?xml version="1.0" encoding="UTF-8"?> 
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<test>toto</test> 
</Document> 

你有什麼想法嗎? 謝謝!

回答

1

您必須設置OutputKeys.DOCTYPE_PUBLIC爲yes

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

謝謝:)馬德漢 –