String strXML ="<?xml version='1.0' encoding='UTF-8' standalone='yes'?><custDtl><name>abc</name><mobNo>9876543210</mobNo></custDtl>"
如何验证字符串是否是正确的 XML 字符串。
您只需根据 XML 字符串打开一个
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 class XmlValidator {
private static final SAXParserFactory SAX_PARSER_FACTORY = SAXParserFactory.newInstance();
static {
// Configure factory for performance and/or security, as needed
SAX_PARSER_FACTORY.setNamespaceAware(true);
// Additional configurations as necessary
}
public static boolean isXMLValid(String xmlContent) {
try {
SAXParser saxParser = SAX_PARSER_FACTORY.newSAXParser();
saxParser.parse(new InputSource(new StringReader(xmlContent)), new DefaultHandler());
return true;
} catch (ParserConfigurationException | SAXException | IOException ex) {
// Optionally handle or log exceptions differently based on type
return false;
}
}
}