Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VALIDATE STRING XML in JAVA

Tags:

java

jaxb

sax

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.

like image 562
user2019331 Avatar asked Aug 13 '15 12:08

user2019331


2 Answers

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
}
like image 78
Sharon Ben Asher Avatar answered Oct 18 '22 19:10

Sharon Ben Asher


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;
    }
}
like image 43
Konstantinos Archimandritis Avatar answered Oct 18 '22 19:10

Konstantinos Archimandritis