Validate string as XML in Java
Asked Answered
C

2

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.

Configuration answered 13/8, 2015 at 12:30 Comment(5)
possible duplicate from #6363426Quote
With a validating XML parser, of course.Introvert
I am able to validate a XML File using SAXParserFactory and SAXParserException. but unable to parse String XMLConfiguration
Also I tried JAXB UnMarshaller for String XML Parsing & it is throwing SAXParserException i am not able to handle..Configuration
Validating a string is not the same as validating a file, not a duplicate.Coursing
N
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
}
Neutralism answered 13/8, 2015 at 13:2 Comment(1)
Thank You. just had to add SAX handler part.Configuration
P
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;
        }
    }
}
Paramedical answered 17/2, 2021 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.