String strXML ="<?xml version='1.0' encoding='UTF-8' standalone='yes'?><custDtl><name>abc</name><mobNo>9876543210</mobNo></custDtl>"
如何验证字符串是否为合适的XML字符串。
String strXML ="<?xml version='1.0' encoding='UTF-8' standalone='yes'?><custDtl><name>abc</name><mobNo>9876543210</mobNo></custDtl>"
InputStream
并将其传递给SAX解析器即可:try {
String strXML ="<?xml version='1.0' encoding='UTF-8' standalone='yes'?><custDtl><name>abc</name><mobNo>9876543210</mobNo></custDtl>";
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
saxParser.parse(stream, ...);
} catch (SAXException e) {
// not valid XML String
}
public static boolean isXMLValid(String string) {
try {
SAXParserFactory.newInstance().newSAXParser().getXMLReader().parse(new InputSource(new StringReader(string)));
return true;
} catch (ParserConfigurationException | SAXException | IOException ex) {
return false;
}
}