下面列出了javax.xml.parsers.SAXParser#parse ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void benchmarkParser(Class parserClass, int n) throws Exception {
long times[] = new long[n];
for(int i = 0; i < n; i++) {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
DefaultHandler viafParser = (DefaultHandler) parserClass.newInstance();
InputStream is = getClass().getResourceAsStream("/shakespeare.xml");
long start = System.currentTimeMillis();
parser.parse(is, viafParser);
long end = System.currentTimeMillis();
times[i] = end - start;
}
System.out.println(String.format("parse using %s, mean time over %s runs=%s", parserClass.toString(), n, mean(times)));
}
/**
* {@inheritDoc}
*/
public BodyParserResults parse(String xml) throws BOSHException {
BodyParserResults result = new BodyParserResults();
Exception thrown;
try {
InputStream inStream = new ByteArrayInputStream(xml.getBytes());
SAXParser parser = getSAXParser();
parser.parse(inStream, new Handler(parser, result));
return result;
} catch (SAXException saxx) {
thrown = saxx;
} catch (IOException iox) {
thrown = iox;
}
throw(new BOSHException("Could not parse body:\n" + xml, thrown));
}
/**
* Extract the scan file and copies it into the temporary folder. Create a new raw data file using
* the information from the XML raw data description file
*
* @param Name raw data file name
* @throws SAXException
* @throws ParserConfigurationException
*/
public RawDataFile readRawDataFile(InputStream is, File scansFile)
throws IOException, ParserConfigurationException, SAXException {
charBuffer = new StringBuffer();
massLists = new ArrayList<StorableMassList>();
newRawDataFile = (RawDataFileImpl) MZmineCore.createNewFile(null);
newRawDataFile.openDataPointsFile(scansFile);
dataPointsOffsets = newRawDataFile.getDataPointsOffsets();
dataPointsLengths = newRawDataFile.getDataPointsLengths();
// Reads the XML file (raw data description)
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(is, this);
// Adds the raw data file to MZmine
RawDataFile rawDataFile = newRawDataFile.finishWriting();
return rawDataFile;
}
/**
* Loads routes from file
*
* @param file valid <code>File</code> with routes
* @return <code>List</code> of <code>Route</code>s
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static List<Route> loadRoutesFromFile(final File file) throws SAXException, IOException, ParserConfigurationException
{
List<Route> routes = new ArrayList<Route>();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = null;
parser = factory.newSAXParser();
parser.parse(file, new GpxParser(file.getName(), null, null, routes));
if (routes.size() > 0)
{
routes.get(0).filepath = file.getCanonicalPath();
}
return routes;
}
@Test
public final void testLargeMaxOccurs() {
String XML_FILE_NAME = "Bug4674384_MAX_OCCURS_Test.xml";
try {
// create and initialize the parser
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser parser = spf.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
File xmlFile = new File(getClass().getResource(XML_FILE_NAME).getPath());
parser.parse(xmlFile, new DefaultHandler());
} catch (Exception e) {
System.err.println("Failure: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs.");
e.printStackTrace();
Assert.fail("Failure: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs. " + e.getMessage());
}
System.out.println("Success: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs.");
}
private static void sendToParser(String b) throws Throwable {
byte[] input = b.getBytes("UTF-8");
ByteArrayInputStream in = new ByteArrayInputStream(input);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser p = spf.newSAXParser();
p.parse(new InputSource(in), new DefaultHandler());
}
Metadata(File metadataXml, File metadataSchema) throws ParserConfigurationException, SAXException, FileNotFoundException, IOException {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setSchema(schemaFactory.newSchema(metadataSchema));
SAXParser sp = factory.newSAXParser();
sp.parse(metadataXml, new MetadataHandler(this));
}
public static ScanHandler read(final URL scanXml) throws IOException {
final SAXParser parser;
try {
synchronized (SAX_FACTORY) {
parser = SAX_FACTORY.newSAXParser();
}
final ScanHandler handler = new ScanHandler();
parser.parse(new BufferedInputStream(scanXml.openStream()), handler);
return handler;
} catch (Exception e) {
throw new IOException("can't parse " + scanXml.toExternalForm());
}
}
@Test(expected = AssertionError.class)
public void resolveXInclude_keepXMLBase() throws SAXException, IOException {
File file = new File("src/test/resources/article.xml");
SAXParser parser = XMLParserUtils.createXIncludeAwareSAXParser(true);
// Fortify mod to prevent External Entity Injections
// The SAXParser contains an XMLReader. getXMLReader returns a handle to the
// reader. By setting a Feature on the reader, we also set it on the Parser.
XMLReader reader = parser.getXMLReader();
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
// End Fortify mods
LegalNoticeHandler handler = new LegalNoticeHandler();
parser.parse(file, handler);
}
/**
*
* @param value
*/
protected void initialize(String value) {
try {
SAXParser saxParser = FACTORY.newSAXParser();
saxParser.parse(new InputSource(new StringReader(value)), this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void validate(Source source, boolean xop, String... schemaLocations) throws TechnicalConnectorException {
try {
XOPValidationHandler handler = new XOPValidationHandler(xop);
ValidatorHandler validator = createValidatorForSchemaFiles(schemaLocations);
ErrorCollectorHandler collector = new ErrorCollectorHandler(handler);
validator.setErrorHandler(collector);
SAXParser parser = SAF.newSAXParser();
parser.parse(convert(source), new ForkContentHandler(new ContentHandler[]{handler, validator}));
handleValidationResult(collector);
} catch (Exception var7) {
throw handleException(var7);
}
}
public static List<FlickrPhoto> getPhotosWithTags(String tags) throws IOException, SAXException, ParserConfigurationException {
LinkedList<FlickrPhoto> photos = new LinkedList<FlickrPhoto>();
URL u = new URL(BASE_URL + "&tags=" + tags);
FlickrPhotoGrabber handler = new FlickrPhotoGrabber();
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
saxParser.parse(u.openStream(), handler);
return handler.photos;
}
static Map<String, Object> getCLDRBundle(String id) throws Exception {
Map<String, Object> bundle = cldrBundles.get(id);
if (bundle != null) {
return bundle;
}
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
enableFileAccess(parser);
LDMLParseHandler handler = new LDMLParseHandler(id);
File file = new File(SOURCE_FILE_DIR + File.separator + id + ".xml");
if (!file.exists()) {
// Skip if the file doesn't exist.
return Collections.emptyMap();
}
info("..... main directory .....");
info("Reading file " + file);
parser.parse(file, handler);
bundle = handler.getData();
cldrBundles.put(id, bundle);
String country = getCountryCode(id);
if (country != null) {
bundle = handlerSuppl.getData(country);
if (bundle != null) {
//merge two maps into one map
Map<String, Object> temp = cldrBundles.remove(id);
bundle.putAll(temp);
cldrBundles.put(id, bundle);
}
}
return bundle;
}
private void loadDefaultContent(
final String domain, final InputStream contentXML, final DataSource dataSource)
throws IOException, ParserConfigurationException, SAXException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
try (contentXML) {
SAXParser parser = factory.newSAXParser();
parser.parse(contentXML, new ContentLoaderHandler(dataSource, ROOT_ELEMENT, true, env));
LOG.debug("[{}] Default content successfully loaded", domain);
}
}
private void parse(URL file, TrackingHandler handler) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
URLConnection connection = file.openConnection();
connection.connect();
this.lastModified = Math.max(this.lastModified, connection.getLastModified());
saxParser.parse(new BufferedInputStream(connection.getInputStream()), handler);
}
catch (Exception ex) {
throw new RuntimeException("Error parsing XML file " + handler.getLineNumberString(), ex);
}
}
public void testSystemMaxOccurLimitWithoutSecureProcessing() {
if (isSecureMode())
return; // jaxp secure feature can not be turned off when security
// manager is present
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
spf.setValidating(true);
setSystemProperty("maxOccurLimit", "2");
// Set the properties for Schema Validation
String SCHEMA_LANG = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
String SCHEMA_TYPE = "http://www.w3.org/2001/XMLSchema";
// Get the Schema location as a File object
File schemaFile = new File(this.getClass().getResource("toys.xsd").toURI());
// Get the parser
SAXParser parser = spf.newSAXParser();
parser.setProperty(SCHEMA_LANG, SCHEMA_TYPE);
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaFile);
InputStream is = this.getClass().getResourceAsStream("toys.xml");
MyErrorHandler eh = new MyErrorHandler();
parser.parse(is, eh);
Assert.assertFalse(eh.errorOccured, "Not Expected Error");
setSystemProperty("maxOccurLimit", "");
} catch (Exception e) {
Assert.fail("Exception occured: " + e.getMessage());
}
}
public static WsdlWrapperHandler parse(File file) throws ParserConfigurationException, SAXException, IOException {
WsdlWrapperHandler handler = new WsdlWrapperHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(file, handler);
return handler;
}
/**
* 加载配置文件
*/
private void loadConfig() {
try {
XMLReader helper = new XMLReader();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(APP.getAssets().open("aria_config.xml"), helper);
FileUtil.createFileFormInputStream(APP.getAssets().open("aria_config.xml"),
APP.getFilesDir().getPath() + Configuration.XML_FILE);
} catch (ParserConfigurationException | IOException | SAXException e) {
ALog.e(TAG, e.toString());
}
}
static Map<String, Object> getCLDRBundle(String id) throws Exception {
Map<String, Object> bundle = cldrBundles.get(id);
if (bundle != null) {
return bundle;
}
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
enableFileAccess(parser);
LDMLParseHandler handler = new LDMLParseHandler(id);
File file = new File(SOURCE_FILE_DIR + File.separator + id + ".xml");
if (!file.exists()) {
// Skip if the file doesn't exist.
return Collections.emptyMap();
}
info("..... main directory .....");
info("Reading file " + file);
parser.parse(file, handler);
bundle = handler.getData();
cldrBundles.put(id, bundle);
String country = getCountryCode(id);
if (country != null) {
bundle = handlerSuppl.getData(country);
if (bundle != null) {
//merge two maps into one map
Map<String, Object> temp = cldrBundles.remove(id);
bundle.putAll(temp);
cldrBundles.put(id, bundle);
}
}
return bundle;
}
public void process(byte[] content) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new ByteArrayInputStream(content), this );
}