5
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.

5
  • 1
    possible duplicate from stackoverflow.com/questions/6362926/… Commented Aug 13, 2015 at 12:35
  • With a validating XML parser, of course. Commented Aug 13, 2015 at 12:40
  • I am able to validate a XML File using SAXParserFactory and SAXParserException. but unable to parse String XML Commented Aug 13, 2015 at 12:43
  • Also I tried JAXB UnMarshaller for String XML Parsing & it is throwing SAXParserException i am not able to handle.. Commented Aug 13, 2015 at 12:47
  • Validating a string is not the same as validating a file, not a duplicate. Commented Jun 29, 2017 at 3:17

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You. just had to add SAX handler part.
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;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.