PrettyXML.java
运行 pretty.bat
package test;
import java.io.*;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/**
* dom4j 学习: 使用dom4j 读取 xml文档并美化输出保存
*
*/
public class PrettyXML {
public static void main(String[] args) throws Exception {
if (args.length ==0){
System.out.println(" usage: java -cp %JAR%;. test.PrettyXML file1.xml ");
return;
}
String f1 = args[0];
if (!f1.endsWith("xml") && !f1.endsWith("XML")){
System.out.println("Error: "+f1+" is not xml file.");
return;
}
File file1 = new File(f1);
if (!file1.exists()){
System.out.println("Error: "+f1+" is not exists.");
return;
}
int i = f1.lastIndexOf(".");
String f2 = f1.substring(0,i) +".out";
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file1);
// 美化格式
OutputFormat format = OutputFormat.createPrettyPrint();
// 指定输出文件
XMLWriter xWriter = new XMLWriter(new FileOutputStream(f2), format);
xWriter.write(document);
xWriter.flush();
xWriter.close();
System.out.println("outfile: "+f2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行 pretty.bat
set JAR=dom4j-1.6.1.jar
set JAR=%JAR%;jaxen-1.1-beta-6.jar
java -cp %JAR%;. test.PrettyXML %1