簡體   English   中英

XML縮進並且沒有獨立的

[英]XML Indent and no standalone

我有一個未格式化的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(true)我有這個結果:

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

與doc.setXmlStandalone(false)我有這個結果:

<?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>

你有想法嗎 ? 謝謝 !

您必須將OutputKeys.DOCTYPE_PUBLIC設置為yes

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM