在java中如何在不终止程序的情况下告诉用户输入的XML字符串无效?
How to tell the user that input XML string is invalid without terminating the program in java?
我正在从文件中读取 XML 个字符串,并希望继续读取后续字符串,即使其中一个字符串的格式无效。那么,当不正确的 XML 字符串出现致命错误时,我该如何继续我的程序呢?
我尝试使用异常处理,但如果 XML 格式不正确,它仍然会出现致命错误。
Document doc = null;
try {
doc = dBuilder.parse(xmlFile);
}
catch(Exception e){
System.out.println(e);
return;
}
这是控制台的样子:-
[Fatal Error] IP.xml:22:24: The element type "ValueDate" must be terminated by the matching end-tag "".
org.xml.sax.SAXParseException; systemId:
file:/D:/Selenium_Workspace/stubvirtualization/IP.xml; lineNumber: 22; columnNumber: 24; The element type "ValueDate" must be terminated by the matching end-tag "".
[致命错误]部分只是一条日志消息,与异常打印无关。
你不需要做任何事情,你可以忽略它并继续。
对我来说很好用...
test.xml:
<xml>
<sda
</xml>
主要方法:
public static void main(String[] args) throws IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = factory.newDocumentBuilder();
Document doc = null;
try {
doc = dBuilder.parse("test.xml");
} catch (SAXException e) {
// do some logging of your own or something
}
System.out.println("done");
}
控制台输出
[Fatal Error] test.xml:3:1: Element type "sda" must be followed by
either attribute specifications, ">" or "/>".
done
我正在从文件中读取 XML 个字符串,并希望继续读取后续字符串,即使其中一个字符串的格式无效。那么,当不正确的 XML 字符串出现致命错误时,我该如何继续我的程序呢?
我尝试使用异常处理,但如果 XML 格式不正确,它仍然会出现致命错误。
Document doc = null;
try {
doc = dBuilder.parse(xmlFile);
}
catch(Exception e){
System.out.println(e);
return;
}
这是控制台的样子:-
[Fatal Error] IP.xml:22:24: The element type "ValueDate" must be terminated by the matching end-tag "". org.xml.sax.SAXParseException; systemId: file:/D:/Selenium_Workspace/stubvirtualization/IP.xml; lineNumber: 22; columnNumber: 24; The element type "ValueDate" must be terminated by the matching end-tag "".
[致命错误]部分只是一条日志消息,与异常打印无关。
你不需要做任何事情,你可以忽略它并继续。
对我来说很好用...
test.xml:
<xml>
<sda
</xml>
主要方法:
public static void main(String[] args) throws IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = factory.newDocumentBuilder();
Document doc = null;
try {
doc = dBuilder.parse("test.xml");
} catch (SAXException e) {
// do some logging of your own or something
}
System.out.println("done");
}
控制台输出
[Fatal Error] test.xml:3:1: Element type "sda" must be followed by either attribute specifications, ">" or "/>".
done