user2019331
user2019331

Reputation: 141

Validate string as XML in Java

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.

Upvotes: 5

Views: 12300

Answers (2)

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;
        }
    }
}

Upvotes: 2

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

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
}

Upvotes: 5

Related Questions