我有一个未格式化的 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");
关于java - XML 缩进并且没有独立的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31007987/