检查xml文件是否符合语法

检查xml文件是否良构的

package validateXML;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
//验证xml是否是良够的,即符合xml语法:(只有一个根元素,开始和结束匹配,正确嵌套,属性值用引号
public class IsXMLavaliable {

public static void main(String[] args){
if(args.length!=1){
System.exit(0);
}

try{
DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(args[0])); //test.xml在当前工程目录下,即在xml目录下
doc.getDocumentElement().normalize();
System.out.println("文档结构正确!");
}
catch(SAXParseException e){
System.out.println("error in line:"+e.getLineNumber()+"file information:"+e.getSystemId());
System.out.println(e.getMessage());
}
catch(SAXException e){
e.printStackTrace();
}
catch(Throwable th){
th.printStackTrace();
}

}
}

你可能感兴趣的:(xml)