在 Java 中将字符串验证为 XML

问题描述 投票:0回答:2
String strXML ="<?xml version='1.0' encoding='UTF-8' standalone='yes'?><custDtl><name>abc</name><mobNo>9876543210</mobNo></custDtl>"

如何验证字符串是否是正确的 XML 字符串。

java jaxb sax
2个回答
6
投票

您只需根据 XML 字符串打开一个

InputStream
并将其传递给 SAX 解析器:

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
}

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;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.