String strXML ="<?xml version='1.0' encoding='UTF-8' standalone='yes'?><custDtl><name>abc</name><mobNo>9876543210</mobNo></custDtl>"
how to validate whether the string is a proper XML String.
String strXML ="<?xml version='1.0' encoding='UTF-8' standalone='yes'?><custDtl><name>abc</name><mobNo>9876543210</mobNo></custDtl>"
how to validate whether the string is a proper XML String.
You just need to open an InputStream
based on the XML String and pass it to the SAX Parser:
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;
}
}
}
© 2022 - 2024 — McMap. All rights reserved.