1.判断文件是否是XML格式
可以通过文件扩展名进行判断,但没法保证文件扩展名正确而内容却不是XML格式.因此可以使用异常进行判断.
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
private static boolean isXmlDocument(File file){
boolean flag = true;
try {
DocumentBuilderFactory foctory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder = foctory.newDocumentBuilder();
builder.parse(file);
flag = true;
} catch (Exception e) {
flag = false;
}
return flag;
}
2.判断字符串是否是XML格式
XML是纯文本,你要判断它整个是否是正确格式,相当于读入全部文件整个进行字符串分析更耗资源!
最简单的方法就是用异常判断。
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
private static boolean isXmlDocument(String rtnMsg){
boolean flag = true;
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
builder.parse( new InputSource( new StringReader( rtnMsg )));
} catch (Exception e) {
flag = false;
}
return flag;
}