String strXML ="<?xml version='1.0' encoding='UTF-8' standalone='yes'?><custDtl><name>abc</name><mobNo>9876543210</mobNo></custDtl>"

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

最佳答案

您只需要基于XML字符串打开InputStream并将其传递给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
}

10-06 16:12